I am trying to plot CSV data (attached) on Google search trends, but the date (year and month) is only appearing as "NaN." How do I plot this?

 Akzeptierte Antwort

Voss
Voss am 15 Apr. 2022

0 Stimmen

The answer depends on how you're reading the file and how you want to deal with the cells in column 2 that say "<1".
One way to do it using readtable:
T = readtable('multiTimeline.csv')
Warning: Column headers from the file were modified to make them valid MATLAB identifiers before creating variable names for the table. The original column headers are saved in the VariableDescriptions property.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table variable names.
T = 220×2 table
Month universalBasicIncome__UnitedStates_ ___________ ___________________________________ {'2004-01'} 5 {'2004-02'} 0 {'2004-03'} 0 {'2004-04'} 0 {'2004-05'} 0 {'2004-06'} 5 {'2004-07'} 0 {'2004-08'} 0 {'2004-09'} 0 {'2004-10'} 0 {'2004-11'} 0 {'2004-12'} 0 {'2005-01'} 0 {'2005-02'} 3 {'2005-03'} 0 {'2005-04'} 0
plot(datetime(T.Month,'InputFormat','yyyy-MM'),T.universalBasicIncome__UnitedStates_)
One way to do it using readcell:
C = readcell('multiTimeline.csv')
C = 222×2 cell array
{'Category: All categories'} {1×1 missing } {'Month' } {'universal basic income: (United States)'} {'2004-01' } {[ 5]} {'2004-02' } {[ 0]} {'2004-03' } {[ 0]} {'2004-04' } {[ 0]} {'2004-05' } {[ 0]} {'2004-06' } {[ 5]} {'2004-07' } {[ 0]} {'2004-08' } {[ 0]} {'2004-09' } {[ 0]} {'2004-10' } {[ 0]} {'2004-11' } {[ 0]} {'2004-12' } {[ 0]} {'2005-01' } {[ 0]} {'2005-02' } {[ 3]}
C([1 2],:) = []; % remove header rows
idx = ~cellfun(@isnumeric,C(:,2)); % replace "<1" or any other
C(idx,2) = {NaN}; % non-numeric entry with a NaN
plot(datetime(C(:,1),'InputFormat','yyyy-MM'),vertcat(C{:,2}));
There are other ways.

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 15 Apr. 2022

0 Stimmen

filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/965680/multiTimeline.csv';
opt = detectImportOptions(filename, 'PreserveVariableNames', true);
opt = setvartype(opt, 1, 'datetime');
opt = setvaropts(opt, 1, 'InputFormat', 'yyyy-MM');
T = readtable(filename, opt);
T(1:2,:)
ans = 2×2 table
Month universal basic income: (United States) _______ _______________________________________ 2004-01 5 2004-02 0

2 Kommentare

econogist
econogist am 15 Apr. 2022
This is great, but how do I plot?
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/965680/multiTimeline.csv';
opt = detectImportOptions(filename, 'PreserveVariableNames', true);
opt = setvartype(opt, 1, 'datetime');
opt = setvaropts(opt, 1, 'InputFormat', 'yyyy-MM');
T = readtable(filename, opt);
plot(T{:,1}, T{:,2})

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Polar Plots finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by