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?

답변 (1개)

Geoff Hayes
Geoff Hayes 2015년 11월 7일

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

MBledsoe
MBledsoe 2015년 11월 9일
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 2015년 11월 9일
I want a one line command, because in reality, my table has multiple "value" columns and several categories.

댓글을 달려면 로그인하십시오.

카테고리

질문:

2015년 11월 7일

댓글:

2015년 11월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by