Plotting hourly values using datetick
조회 수: 11 (최근 30일)
이전 댓글 표시
I have a vector of size (1x8424) which has values for the first 8424 hours of year 2014. I want to plot this vector (x-axis I will have the months of 2014 and on the y-axis I will have the output from my vector). Is there a way to do this automatically. I understand I can make use of datetick but how should I formulate my xData vector (since my hourly vector does not stop at 31-12-2014)?
댓글 수: 0
답변 (1개)
Brian Neiswander
2015년 8월 17일
편집: Brian Neiswander
2015년 8월 17일
One approach is to explicitly set the "XTick" property of the axes using date number values. As an example, let's assume that you have sample data for the first 8424 hours of 2014:
%make some sample data with the first 8424 hours of 2014
x = datetime(2014,1,1,1,0,0):hours(1):datetime(2014,1,1,8424,0,0);
y = sin(2*pi*linspace(0,1,length(x)));
Note the "datetime" function used above is available in MATLAB R2014b and later. We can plot this data in a figure:
%plot the data
figure;
plot(x,y);
xlabel('Month in 2014');
ylabel('Output');
On my MATLAB R2014b, the output looks like this:
Now, to change the x-axis to include all month names in 2014, you can explicitly set the tick values. To do this, we first need an array containing all the of the months in 2014:
%get all the months of 2014
allMonths = datetime(2014,1,1,0,0,0):calmonths(1):datetime(2014,12,31,0,0,0);
Now, we can set the "XTick" property of the axes to create ticks at each of these month values. In order to do this, we also need to convert the sting values in "allMonths" into date numbers using the "datenum" function:
%set the x-ticks of the plot to be the datenumbers for each month
set(gca,'XTick',datenum(allMonths));
Finally, to make sure that "January" and "December" show up, let's set the x-axis limits to range to include the first and last months of 2014:
%set the x-axis limits to include the first and last months
xlim(datenum([allMonths(1),allMonths(end)]));
On my MATLAB R2014b, the output now looks like:
See the documentation links below for more information.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!