Boon
Boon

Reputation: 1173

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

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.

Upvotes: 1

Views: 505

Answers (2)

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22245

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.

Upvotes: 0

FangQ
FangQ

Reputation: 1544

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)

Upvotes: 2

Related Questions