How to plot lines for each category in a table?

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?

Réponses (1)

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 commentaires

MBledsoe
MBledsoe le 9 Nov 2015
Thanks for the swift reply, Geoff. I figured that I could write a loop to do it, but I was hoping there was a simpler way, like how you can do scatter plots or box plots by group with one command (gscatter and boxplot, respectively).
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
MBledsoe le 9 Nov 2015
I want a one line command, because in reality, my table has multiple "value" columns and several categories.

Connectez-vous pour commenter.

Commenté :

le 9 Nov 2015

Community Treasure Hunt

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

Start Hunting!

Translated by