Adding error bars to a grouped bar plot

603 vues (au cours des 30 derniers jours)
Shanaja
Shanaja le 6 Jan 2019
Hi! I’m trying to plot a grouped bar graph with standard errors, and have managed this so far, which almost works but the SE are for some reasons plotted next to the bars rather than on them (see attached)? Any idea how to fix it? Thanks!
err = [3, 3; 1, 3];
 
y=[69,123; 74, 62];
figure
bar(y)
set(gca, 'XTickLabel', {'Cats' 'Dogs'});
hold on
errorbar(y, err, '.')
ylabel('Mean Error');
ylim([20 140]);
legend('response to novel cats', 'response to novel dogs');
saveas(gcf,['bar_2', '.jpg'])

Réponse acceptée

Vishal Chaudhary
Vishal Chaudhary le 9 Jan 2019
The ability to specify that the "errorbar" function display the error bars inside the individual bars is not available in MATLAB. It displays errorbar at the center of each group.
To work around this issue, find the center of each bar and pass this data into "errorbar" with the respective error values.
ngroups = size(y, 1);
nbars = size(y, 2);
% Calculating the width for each bar group
groupwidth = min(0.8, nbars/(nbars + 1.5));
for i = 1:nbars
x = (1:ngroups) - groupwidth/2 + (2*i-1) * groupwidth / (2*nbars);
errorbar(x, y(:,i), err(:,i), '.');
end
hold off
  4 commentaires
David L
David L le 29 Oct 2019
This was super helpful. Thank you!!
CR
CR le 18 Juin 2020
This is great! Would it be possible to decrease the spacing between the grouped bars? Thanks again!

Connectez-vous pour commenter.

Plus de réponses (2)

Steve Schaefer
Steve Schaefer le 11 Mar 2020
  2 commentaires
Jonathan Cottet
Jonathan Cottet le 19 Avr 2021
The code for the graph is not really displayed in the link you posted (categorical graph in your picture). Could you please post it here ?
Thanks in advance !
z8080
z8080 le 20 Juin 2023
@Steve Schaefer, I would second @Jonathan Cottet's request to please post that code, as it is in fact not to be found under the given link. Thanks!

Connectez-vous pour commenter.


Star Strider
Star Strider le 20 Juin 2023
An example using properties available in prior and recent MATLAB releases is provided in Putting error bars on bar plot?
One of these approaches should work for all releases (at least after R2014b when ‘Handle Graphics 2’ appeared, and perhaps for earlier releases as well). The same general approach will also work for putting numbers or other text objects above or within the bars.

Catégories

En savoir plus sur Data Distribution Plots dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by