I want to plot a grouped bar graph like in the figure below:
I've included a mock-up of the data I'm using:
I want to group the bars by SampleSite
, label them by SampleName
, and color them by Category
. I've tried the following code, and while it gives me something close to what I'm looking for, I'm unsure how to get the data grouped and colored by the column values.
y1= samples(MockUp_Data.SampleSite== "Site1", :);
y2= samples(MockUp_Data.SampleSite== "Site2", :);
y3= samples(MockUp_Data.SampleSite== "Site3", :);
y= [y1;y2;y3];
bar(y.Data)
set(gca, 'xticklabels', char(y.SampleName), 'fontweight', 'bold', 'fontsize', 12)
I want to group the bars by
SampleSite
, label them bySampleName
, and color them byCategory
.
pivot
your current "long" table into a "wide" table:
SampleSite
(group) per rowCategory
(color) per columnP = pivot(MockUp_Data, ...
'Rows', 'SampleSite', ...
'Columns', 'Category', ...
'DataVariable', 'Data')
% P =
%
% 3x5 table
%
% SampleSite Bulk Coarse Fine Mud
% __________ ____ ______ ____ ___
%
% "Site 1" 4.5 6 2 3.1
% "Site 2" 5.5 6.7 8 10
% "Site 3" 12 3.3 2 5
Now we have x in column 1, y in columns 2:end
, and legend entries in headers 2:end
:
bar(P{:,1}, P{:,2:end})
legend(P.Properties.VariableNames{2:end})
Note that your text description and mock figure are flipped (former is grouped by SampleSite
, latter is grouped by Category
). To follow your mock figure, flip the rows and columns while pivoting:
P = pivot(MockUp_Data, ...
'Rows', 'Category', ...
'Columns', 'SampleSite', ...
'DataVariable', 'Data')
bar(P{:,1}, P{:,2:end})
legend(P.Properties.VariableNames{2:end})