How to specify date ticks on plot

238 views (last 30 days)
I'm trying to plot the attached csv file, but i am having problems creating a tidy x axis labels. Ideally, I would like a label to read: 2000, 2004, 2008, 2012, 2016, 2020, starting on the earliest date for each year. However, despite trying to set my xtick using a string converted through datenum, I can't figure out how to achieve this result. My code, with the neatest labels I can manage, is attached, but this doesn't produce my desired labels. Any suggestions?
%plots the price of copper from
close all;
fid = fopen('copper-prices-historical-chart-data.csv');
if fid>0
% note how we skip the header lines and use the delimiter
data = textscan(fid,'%s %f','Delimiter',',','HeaderLines',16);
% close the file
startlim = datenum('07-Jan-2000');
endlim = datenum('31-Mar-2020');
date = data{1,1};
dn = datenum(date, 'yyyy-mm-dd');
price = data{1,2};
dateplot = dn(10141:end);
priceplot = price(10141:end);
xlim([startlim, endlim]);
Thanks in advance.

Accepted Answer

Star Strider
Star Strider on 9 Mar 2020
Try this:
TCu = readtable('copper-prices-historical-chart-data.csv');
startlim = '07-Jan-2000';
endlim = '31-Mar-2020';
GetRows = isbetween(, startlim, endlim);
plot(, TCu.value(GetRows))
xlim([datetime('01-Jan-2000') datetime('31-Dec-2020')])
xticks(datetime('01-Jan-2000') : calyears(4) : datetime('31-Dec-2020'))
The datetime functions require R2014b or later.
Star Strider
Star Strider on 9 Mar 2020
As always, my pleasure!

Sign in to comment.

More Answers (1)

Adam Danz
Adam Danz on 9 Mar 2020
Convert your dates to datetime values using datetime().
Then use xtickformat('yyyy') to set the datetime format for the x-tick values.
Adam Danz
Adam Danz on 8 Dec 2021
Is your time vector in datetime format? If not, convert it to datetime format and use that vector for your x-variable when plotting so the ticks are in datetime format.

Sign in to comment.


Find more on Dates and Time 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!