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?

 Akzeptierte Antwort

dpb
dpb am 18 Aug. 2015
Bearbeitet: dpb am 20 Aug. 2015

0 Stimmen

[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 Kommentare

Ivan Q
Ivan Q am 18 Aug. 2015
I was getting some errors so I rewrote the code to this:
fid = fopen( 'file.txt' );
A=textscan(fid,'%8s %f %f');
x=A{2};
y=A{3};
dn=datenum(A{1},'hh:mm:ss');
plot(dn,y)
datetick('x','HH:MM:SS')
However, dn cycles between values of 7.3706 and 7.3606 and my x-axis does not show up as a time. How do I get the X-axis to display my exact time strings ie. 13:58:38
Ivan Q
Ivan Q am 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 am 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...

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Large Files and Big Data finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 18 Aug. 2015

Bearbeitet:

dpb
am 20 Aug. 2015

Community Treasure Hunt

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

Start Hunting!

Translated by