Plotting timetable data: how to add x-axis ticks, labels and gridlines on 1st and 15th day of each month
Show older comments
I have a timetable with mean daily air temperature data recorded for nine months (1st June 2018 to 1st March 2019).

I would like to plot it with:
- x-axis ticks, labels and major gridlines on 1st day of each month
- x-axis ticks and minor gridlines on 15th day of each month.
Currently I have the following code, which adds 10 equally spaced ticks, labels and gridlines (more or less every 30 days):
% Create a plot, set axis limits and y label
plot(indata.time,indata{:,1});
xlim(datetime([2018 2019],[6 3],[1 1]))
ylabel('Mean Ta (*C)');
% Add equally spaced ticks (one every ~30 days)
xData = linspace(indata1.time(1),indata1.time(end),10);
d.XTick = xData;
% Add labels
tx = get(gca,'XTickLabel'); set(gca,'XTickLabel',tx,'fontsize',fsize,'FontWeight','bold');
ty = get(gca,'XTickLabel'); set(gca,'XTickLabel',ty,'fontsize',fsize,'FontWeight','bold');
datetick('x','dd mmm yy','keeplimits','keepticks');
% Add gridlines
hAx=gca;
set(hAx,'YGrid','on','XGrid','on')
set(hAx,'xminorgrid','on','yminorgrid','on')
which results in this figure:

Is there a simple way to:
1) set ticks, labels and major gridlines on 1st day of each month?
2) add minor gridlines? (my code works fine with minor horizontal gridlines, but not vertical ones)
Thanks in advance!
Accepted Answer
More Answers (1)
Roger Parkyn
on 20 May 2021
Another way to get a vector of monthly datetimes to use for the ticks would be:
t_monthly=[datetime(2018,6,1):calmonths(1):datetime(2019,3,1)].'
then can use the abovementioned:
hAx.XAxis.MinorTickValues=t_monthly; % set minor tick locations
The mid-month times could be:
t_mid_monthly = t_monthly(1:end-1) + days(15);
Categories
Find more on Axis Labels in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!