Sofia June
Sofia June

Reputation: 169

How to label x-axis with dates?

I cant seem to figure out how to plot dates in Matlab that aren't in numerical order. The dates I need are from January 22nd to Feburary 1st, but when I put it in Matlab it goes in numerical order starting from the 1st. So I was wondering how to get it so that it goes in order of the list I have.

Here is the code I've made:

date = [22 23 24 25 26 27 28 29 30 31 1 2 3 4];
in_bed = [3 8 26 76 225 298 258 233 189 128 68 29 14 4];
convalescent = [0 0 0 0 9 17 105 162 176 166 150 85 47 20];
plot(date,in_bed,'*',date,convalescent,'*')
xlabel('Janurary -- Feburary')
ylabel('Number of Cases')
legend('Confined to bed','Convalescent')
title('Influenza Outbreak')

Upvotes: 3

Views: 629

Answers (3)

Robert Seifert
Robert Seifert

Reputation: 25232

Have you thought about working with the actual date format? This way your time arguments stay in chronological order.

First do some preparations:

days = [22 23 24 25 26 27 28 29 30 31 1 2 3 4];
months = [1 1 1 1 1 1 1 1 1 1 2 2 2 2];
year = repmat(2015,numel(days),1);

in_bed = [3 8 26 76 225 298 258 233 189 128 68 29 14 4];
convalescent = [0 0 0 0 9 17 105 162 176 166 150 85 47 20];

Create a datevec (date vector)

dateVector = [year(:) months(:) days(:)];

and convert it to a double value with datenum:

date = datenum(dateVector); 

Plot and fix the x-ticks

plot(date,in_bed,'*',date,convalescent,'*')
set(gca,'XTick',date)  %// if you leave this step, labeling is dynamic!

Define the format of your labels with datetick:

datetick('x','dd-mm','keepticks')

and voilà: enter image description here

Upvotes: 5

scmg
scmg

Reputation: 1894

First, use the following xData instead of date in plot:

startDate = datenum('01-22-2014');
endDate = datenum('02-04-2014');
xData = linspace(startDate, endDate, endDate - startDate + 1);

Then, set ticks with datetick and keeplimits option:

datetick('x','mm-dd-yyyy','keeplimits');

Upvotes: 2

casillas
casillas

Reputation: 16793

Check the following link :http://www.mathworks.com/help/matlab/ref/datetick.html

ax1.XTick = xData;
datetick(ax1,'x','mm','keepticks')

ax2.XTick = xData;
datetick(ax2,'x','mmm','keepticks')

Upvotes: 2

Related Questions