Plot time series in date format from Excel sheet
조회 수: 3 (최근 30일)
이전 댓글 표시
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
채택된 답변
Star Strider
2021년 12월 15일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Spreadsheets에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!