How to plot lines for each category in a table?
Mostrar comentarios más antiguos
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?
Respuestas (1)
Geoff Hayes
el 7 de Nov. de 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 comentarios
MBledsoe
el 9 de Nov. de 2015
Peter Perkins
el 9 de Nov. de 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
el 9 de Nov. de 2015
Categorías
Más información sobre Bar Plots en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!