Plot data with time

5 views (last 30 days)
Ivan Q
Ivan Q on 18 Aug 2015
Edited: dpb on 20 Aug 2015
I'm trying to plot my data with time on the x-axis. My data has the following csv format:
13:05:48 1.33 5.15
13:05:53 2 5.2
13:05:58 2.1 4.88
There are 3 columns with column 1 being my time(HH:MM:SS) and column 2 and 3 being my data. How do I read then plot Column 1 time vs. my column 2 or 3?

Accepted Answer

dpb
dpb on 18 Aug 2015
Edited: dpb on 20 Aug 2015
[d,x,y]=textread('ivan.csv','%8s %f %f','delimiter',' ');
dn=datenum(d,'HH:MM:SS'); % ERRATUM: had lowercase in time format string
plot(dn,[x y])
datetick('x')
Alternatively, use textscan or with the latest releases there's a new datetime object
  3 Comments
Ivan Q
Ivan Q on 19 Aug 2015
I was able to accomplish what I wanted with the following code:
%%Open data and separate cells
fid = fopen( 'Data.txt' );
A=textscan(fid,'%8s %f %f');
x=A{2};
y=A{3};
dn=datenum(A{1},'HH:MM:SS'); %change string into datenum
%%plot figure
plot(dn,x*2)
hold on
plot(dn,y)
%%Set x-axis
l=length(dn)
set(gca, 'XTick', (dn(1) : .001 : dn(l)) )
datetick('x','HH:MM:SS','keepticks')
dpb
dpb on 20 Aug 2015
Ah, yes, I carelessly used lower case for the time fields in the format string; that's an error, sorry. Checked that the textread worked right but didn't actually look a the the returned times on the axes, only that they were actually formatted as dates...I fixed up the Answer altho you've uncovered the problem.
I tend to use textread where I can even though it has been relegated to "red-haired stepchild" status by TMW as it doesn't require the extra step of fopen/fclose and returns char and double arrays where don't need or want cell arrays. It does require a separate variable for each field which can be a nuisance and can't handle all cases that textscan can, but for simple file structures it's a better option imo still. Anyway, that's an aside not related to the actual problem here...

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!