user2861089
user2861089

Reputation: 1235

plot a bar chart of data grouped by categories in matlab

In matlab, is it possible to plot a bar chart of data grouped by categories?

For example, say I have imported an excel file containing the following columns of data:

Year    Month    Species    Count
2005      2       spider      5
2005      4      mosquito     8
2006      1       midge       4
2008      4       spider      3

The figure should have time along the x-axis (months and years) and Count on the y-axis. A grouped bar chart (different colours for different species) should be plotted at the corresponding time points (note that there are missing time points when Count=0).

Upvotes: 1

Views: 1018

Answers (1)

David
David

Reputation: 8459

Here is an example, with some randomly generated data. You will have to check the matrix D and see if it structured the same as your data.

clear,clc,close
Y=[2013:1:2014];
for i=1:length(Y)
    for j=1:12
        for k=1:3
            D(i,j,k)=randi(5)-1;
        end
    end
end

for i=1:3
    t=squeeze(D(:,:,i)).';
    M(:,i)=t(:).';
end
bar(M)

I am assuming that you can create D to be the same as I did. You will need to convert the strings in Species to numbers using, e.g.:

Species={'spider';'midge';'mosquito';'spider'}
S=zeros(size(Species))
S(strcmp(Species,'spider'))=1
S(strcmp(Species,'midge'))=2
S(strcmp(Species,'mosquito'))=3

then D=[Year Month S Count].


Hopefully the idea helps you at least.

Upvotes: 0

Related Questions