How to plot lines for each category in a table?
Show older comments
Suppose I have a table with three columns: a date, a categorical array, and values that vary by date and category. For example, the table may contain the annual GDP growth for the US, England, and Japan from 1980 - 2014. So, the date column would have three copies of 1980:2014 stacked on top of each other; the categorical array would have a label for the country for each set of years; and, the values would be the GDP growth for the given date and country.
Is there an easy (one line) way to plot all three country's GDP series (years on the x-axis, GDP growth on the y-axis) on the same chart using the categorical array?
Answers (1)
Geoff Hayes
on 7 Nov 2015
Why do you need a one line command to plot the data since there are only three countries? Can't you do something like the following to plot the GDP for each country?
% get the unique countries
countryNames = unique(myTable.Country);
figure;
hold on;
for k=1:length(countryNames)
% get the row indices for the kth country
rowIdcs = strcmpi(myTable.Country,countryNames{k});
% get the years for this country
years = myTable.Year(rowIdcs);
% get the GDP
gdpPerYear = myTable.GDP(rowIdcs);
% plot the data
plot(years,gdpPerYear,'color',rand(1,3));
end
legend(countryNames);
The above is untested (since I don't have your table) but you should be able to modify the above to suit your needs.
3 Comments
MBledsoe
on 9 Nov 2015
Peter Perkins
on 9 Nov 2015
A minor point: since Country is a categorical, this line
rowIdcs = strcmpi(myTable.Country,countryNames{k})
can be written as
rowIdcs = myTable.Country == countryNames{k}
MBledsoe
on 9 Nov 2015
Categories
Find more on Bar Plots 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!