How do I plot a table with dates?

Hi! I am trying to plot a table, this is a short snippet of it:
date CountryA CountryB CountryC
_____ _______ _______ _______
2020-01-01 {[ 17]} {[ 18]} {[ 12]}
2020-01-02 {[ 15]} {[ 13]} {[ 16]}
2020-01-03 {[ 20]} {[ 15]} {[ 16]}
I am attempting to do this by using this:
plot(T{:,1},T{:,2:4})
It gives me this error:
Error using plot
Invalid data argument.
What's wrong with it and how can I fix it?

 Accepted Answer

VBBV
VBBV on 13 Nov 2020
Edited: VBBV on 13 Nov 2020
T = table({'2020-01-01';'2020-01-02';'2020-01-03'},[17;15;20],[18;13;15],[12;16;16],'VariableNames',{'Date','Country A','Country B','Country C'})
TT = table2cell(T)
T1 = datetime(TT(:,1))
plot(T1,cell2mat(TT(:,2:4)))
ax = gca; set(ax,'XTickLabels',{'1 Jan 2020', '','3 Jan 2020','', '5 Jan 2020'})

2 Comments

No, don't do that. There's no need to convert to and from a cell array.
Scarlett, you have (it appears) a table with one datetime variable and three variables that should be numeric but are in fact cell arrays. That's bad for several reasons, not the least of which is that you won't be able to do anything useful with the numeric data in cell arrays. You need to figure out why you are ending up with that table. One wild guess might be that you are using xlsread when you should be using readtable. In fact, what you want to have is a timetable.
One you remedy that, then what you have, plot(T{:,1},T{:,2:4}), will work. You may find this more readable:
plot(T.date,T.CountryA, T.date,T.CountryB, T.date,T.CountryC)
but your use of brace subscripting to extract the datetimes and the numbers is correct, but I'd suggest
plot(T.date,T{:,["CountryA" "CountryB" "CountryC"]})

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2020a

Tags

Community Treasure Hunt

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

Start Hunting!