Plotting hourly values using datetick

12 views (last 30 days)
Eli Dim
Eli Dim on 14 Aug 2015
Edited: Brian Neiswander on 17 Aug 2015
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)?

Answers (1)

Brian Neiswander
Brian Neiswander on 17 Aug 2015
Edited: Brian Neiswander on 17 Aug 2015
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.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by