フィルターのクリア

How to specify date ticks on plot

107 ビュー (過去 30 日間)
Ted Baker
Ted Baker 2020 年 3 月 9 日
コメント済み: Adam Danz 2021 年 12 月 8 日
Hi,
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 https://www.macrotrends.net/1476/copper-prices-historical-chart-data
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
fclose(fid);
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);
plot(dateplot,priceplot);
xlim([startlim, endlim]);
xticks=get(gca,'xtick');
xtickangle(45);
set(gca,'xticklabel',cellstr(datestr(xticks))')
end
Thanks in advance.

採用された回答

Star Strider
Star Strider 2020 年 3 月 9 日
Try this:
TCu = readtable('copper-prices-historical-chart-data.csv');
startlim = '07-Jan-2000';
endlim = '31-Mar-2020';
GetRows = isbetween(TCu.date, startlim, endlim);
figure
plot(TCu.date(GetRows), TCu.value(GetRows))
grid
xlim([datetime('01-Jan-2000') datetime('31-Dec-2020')])
xtickformat('yyyy')
xticks(datetime('01-Jan-2000') : calyears(4) : datetime('31-Dec-2020'))
producing:
The datetime functions require R2014b or later.
  2 件のコメント
Ted Baker
Ted Baker 2020 年 3 月 9 日
Thank you very much for that example, Star Strider. It works perfectly.
Star Strider
Star Strider 2020 年 3 月 9 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (1 件)

Adam Danz
Adam Danz 2020 年 3 月 9 日
Convert your dates to datetime values using datetime().
Then use xtickformat('yyyy') to set the datetime format for the x-tick values.
  4 件のコメント
Ravi
Ravi 2021 年 12 月 8 日
I have data which is time dependent but time data is not avaialble. I needed to plot this data with time so I created time loop with size matching up with the data size. I am able to get the plot but now I need to put in my desired time ticks on time axis. How can I do this ?
Adam Danz
Adam Danz 2021 年 12 月 8 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeTime Series Objects についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by