Plot time series in date format from Excel sheet
3 views (last 30 days)
Show older comments
Achuan Chen
on 15 Dec 2021
Commented: Star Strider
on 15 Dec 2021
The Excel sheet attached contains a date column, which is in the format dd/mm/yyyy.
I would like to create a time-series plot for the prices contained in table A, with the date displayed on the x-axis.
I've tried to convert the dates in the 'date' column to datetime type, then use the plot() function to create the plot, but apparentlty it is of the wrong data type.
My code:
opts = detectImportOptions('fruitvegprices.csv');%detects import options for the file
opts = setvartype(opts,["variety"],"categorical");%changes variety to categorical
data = readtable('fruitvegprices.csv',opts);%import spreadsheet
%apples
apples = data(data.item=="apples",:); %table of just apples
uniq_apples=unique(apples.variety,'stable');%distinct varieties of apple
item=uniq_apples(8);
A=apples(ismember(apples.variety,item),:)
ts=timeseries(A.price);
date = datetime(A.date,'InputFormat','dd-mmmm-yyyy')
plot(date,ts)
How could I resolve this?
Thank you!
0 Comments
Accepted Answer
Star Strider
on 15 Dec 2021
There is nothing wrong with the dates.
Try something like this —
T1 = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/834340/fruitvegprices.csv', 'VariableNamingRule','preserve')
[G,ID] = findgroups(T1.variety) % Group By 'variety'
Gu = unique(G); % Number Of Unique Groups (Information Only, Not Needed For Code)
T1.price(G==G(1),:); % Checking Indexing
figure
plot(T1.date(G==G(7),:), T1.price(G==G(7),:))
hold on
plot(T1.date(G==G(4),:), T1.price(G==G(4),:))
plot(T1.date(G==G(5),:), T1.price(G==G(5),:))
plot(T1.date(G==G(6),:), T1.price(G==G(6),:))
plot(T1.date(G==G(8),:), T1.price(G==G(8),:))
hold off
grid
str = strrep(ID([7 4 5 6 8]), '_','\_');
legend(str, 'Location','best')
xlabel('Date')
ylabel('Price (€)')
Experiment!
.
2 Comments
More Answers (0)
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!