Matlab/Octave - parsing and plotting date string vs. integer

拜拜、爱过 提交于 2021-01-28 08:32:08

问题


I have a data file with the first column as date strings and the second column an integer:

"2020/02/29" 1
"2020/03/03" 2
"2020/03/04" 6

I want to parse this file and plot the date on the x-axis and the integer on the y-axis. My most recent failing attempt is:

file_name = "data.dat";
fid = fopen(file_name, 'rt');
raw_data = textscan(fid, "%s %d");
fclose(fid);

graphics_toolkit('gnuplot');
plot(raw_data(:, 1), raw_data(:, 2));

The graph is empty with no data to show. How can I properly plot such data? It seems the output of textscan is a little unwieldy for plotting.


回答1:


you can't plot a string, you must convert the date string to a date number first. use cellfun to do this efficiently

x=cellfun(@(d) datenum(regexprep(d,'"',''),'yyyy/mm/dd'), raw_data{1});
y=raw_data{2};
plot(x,y)



回答2:


This would be my way of doing it.

pkg load io

Data   = csv2cell( 'data', ' ' );
Rows   = size( Data, 1 );

Datestrings = cell( Rows, 1 );
Datenums    = zeros( Rows, 1 );
Values      = zeros( Rows, 1 );

for i = 1 : Rows
  Datestrings{i} = Data{ i, 1 };
  Datenums(i)    = datenum( Data{ i, 1 }, 'yyyy/mm/dd' );
  Values(i)      = Data{ i, 2 };
end

plot( Datenums, Values );
set( gca, 
     'xtick', Datenums, 
     'xticklabel', Datestrings
);

I would have added an xticklabelrotation option too, but alas according to the manual, xticklabelrotation is not yet implemented in current octave (5.2.0), so adding it doesn't do anything.



来源:https://stackoverflow.com/questions/61028154/matlab-octave-parsing-and-plotting-date-string-vs-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!