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
2015년 11월 7일
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
2015년 11월 9일
Peter Perkins
2015년 11월 9일
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
2015년 11월 9일
카테고리
도움말 센터 및 File Exchange에서 Bar Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!