Problem with "grouped" bar plot
12 views (last 30 days)
I am using the following code to produce a "grouped" bar plot (4 groups and 2 subgroups, respectively). Now, I would like to use 8 different colors (1 for each bar) because the 2 subgroups are not the same for each group. I am confused why only two different colors are applied here. Actually, this is not a real grouped bar plot since I am not using b = bar(model_series, 'grouped'), isn't it?
I hope the problem became clear. Any help appreciated.
figure1 = figure;
axes1 = axes('Parent',figure1);
b = bar(model_series,'Parent',axes1);
% Find the number of groups and the number of bars in each group
[ngroups, nbars] = size(model_series);
% Calculate the width for each bar group
groupwidth = min(0.8, nbars/(nbars + 1.5));
for i = 1:nbars
% Calculate center of each bar
x = (1:ngroups) - groupwidth/2 + (2*i-1) * groupwidth / (2*nbars);
errorbar(x, model_series(:,i), model_error(:,i), 'k', 'linestyle', 'none');
% Set the remaining axes properties
set(axes1,'XTick',[1 2 3 4],'XTickLabel',...
dpb on 30 Jul 2021
"... this is not a real grouped bar plot since I am not using b = bar(model_series, 'grouped'), isn't it?"
Au contraire, the documentation says
"bar(y) creates a bar graph with one bar for each element in y. If y is an m-by-n matrix, then bar creates m groups of n bars."
and your data are 4x2. Hence you have a grouped bar plot with two groups and therefore, two bar objects and two bar colors.
NB: the 'XEndPoints' property is in the bar handle now to be able to use for the X positions needed so can write as
To change the bar colors, have to use subterfuge;
and then set the .CData color triplet data for each bar as wanted -- each of the four bars in each group is a line in the .CData array. There is an example in the documentation for bar