File Exchange

image thumbnail


version (6.17 KB) by Martina Callaghan
This is a very simple extension of MatLab's bar function to add error bars.


Updated 03 Jun 2018

View Version History

View License

Released Code; update to draw graphics immediately.

Cite As

Martina Callaghan (2021). barwitherr(errors,varargin) (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (119)

Ece Kaya

Jun Liu

Simple works best. Much better than barweb.



Serhii Tetora

one bug?
y = randn(3,4); % random y values (3 groups of 4 parameters)
errY = zeros(3,4,2);
errY(:,:,1) = 0.1.*y; % 10% lower error
errY(:,:,2) = 0.2.*y; % 20% upper error
[hBar, hErrorbar] = barwitherr(errY, y); % Plot with errorbars


>>hErrorbar =

0.0082 1.0082 2.0072 4.0071

Andres Sastoque

Jonathan Poli

Rob Feldmann

Jason Yves Tissières

Rohan Kulkarni

How can you change the color scheme of the bars?

Benji Obikenobi


Maxandre Jacqueline

I worked around my problem for if x is categorical by calling:
gca.XAxis.TickLabels = x_categorical;

Maxandre Jacqueline

Great but doesn't work when x is categorical. It would be amazing if you could make it work in that case.

Lionel Arteaga


Jonas Wielinski

James Adinata

Brandon Cummings

Worked exactly as advertised, out of the box. Thank you!

Hi, is there anyway to change the thickness of the error bars or customize it?

Martina Callaghan

Hi Oscar, this would only be the case if y is a vector not a matrix. In this case the bars are separated by group (x-axis) rather than colour. If y is a matrix then hBar will have an entry for each column of y and the face colour for these can be individually set.

Oscar Knights

I can't seem to change the 'facecolor' of each bar separately - they all change to the same colour.

set(hBar(1),'facecolor','b') - changes all bars to blue

set(hBar(2),'facecolor','r') - gives error "index exceeds matrix dimensions"

There only appears to be 1 bar in the handle, but 4 bars are plotted. Any ideas?

Paloma Garrido Amador

Thank you very much, it works perfectly!

Martina Callaghan

Hi Harsh, yes you can have variable errors - these are passed as a matrix.

Martina Callaghan

Mahlet, yes, you can plot values, e.g.:


Matt Learner

Tim Blackmore

Worked perfectly. Thank you.

Mahlet Zewde

Hei, Is it possible to plot values on the x axis?

Miro Grundei

Very nice solution !!!

Almut Heinken

Great, exactly what I needed.

Adrian Juncos

Can somebody tell me how to use this extension? I can't really make heads or tails of it.

James Moreland

Fantastic. Immediately did what I wanted.

Great job, thank you

Janja Dermol

Really helpful, thank you.



Fidan Sümbül

Liguo Yang

that is really helpful, thank you very much


very easy to use!

Antonio Verdone

Sahar Mahmoudi

Mark Does

Mohamed Abdelkareem

Luca Lo Verde

Daniel Charlebois

Exactly what I needed. Thanks!

Is there a way to change the color of error bars?



Is there any way I can provide different error for different group and parameters?

I have a single parameter and multiple groups with symmetric error but different for each group(e.g. Group 1:10%, Group 2:30%, Group 3:20%).

Any help?

Nivedita Rangarajan



Great! Note that hold must be off before calling this function.


Pedram Ramin

Pedram Ramin

nice job

Nico Zuo

@Parto Parto's question indeed exists, since the get(h0, 'children') function can not get the individual bar which is the way in original bar function in Matlab. For example, Y=rand(1,3); eY=rand(1,3);
h1=get(h0, 'children');
Here, the h1 is not a cell which contains individual bar.

Martin Schrimpf


Very simple & works fine for me! Good job!

Paolo Inglese

Jhonatan Soto

Thanks, I was suffering with this, clever solution :)


I'm not sure if this has been commented already or not. I'm using MATLAB 2015a and the hErrorbar object array output wasn't working correctly. I found the hErrorbar array preallocation (line 120) to be the problem. Commenting it out solved it. The appropriate fix would be to preallocate the object array somehow else, but I'm quite a beginner and I'm not sure how to do it.

zong zhang

very clear and useful

Paolo Inglese


very effective function. Thank

Ben de Monsabert

Hi everyone,

The function is no longer working with Matlab R2015a and R2015b.

Because the graphics are now handled differently, the position of the middle of each bar in a grouped bar series can no longer be obtained using :

x = + [];

After searching on the forum and on the web, I found a solution that worked for me

For Matlab version R2015a and R2015b, the line above should be replaced (see Link 1 below) by :

x = bsxfun(@plus, hBar(col).XData, [hBar(col).XOffset]');

If this does not work (see Link 2 below), another line must be added before:

x = bsxfun(@plus, hBar(col).XData, [hBar(col).XOffset]');

Hope it will help other R2015 users continue using this great function.


Link 1:


Guillermo David

Hi everyone!

I would like exactly this .m but with the posibility to plot in horizontal. Any ideas?

Have a nice week!

James Rankin

>> Now updated for 2014b - thanks Jiri for the linke.

I had to also add a drawnow after line 115: = bar(varargin{:});

This is a bit weird, but the wasn't properly initialised (XOffset used later would be 0) until the plot command had been allowed to execute...

Incidentally this was on Ubuntu 14.04.

Thanks for a useful function Martina!

Jatin Gera

Martina Callaghan

Hi Eric,

I would suggest simply generating the plot and then applying a grayscale colour map. That's how I convert my figures for papers.

(>> colormap gray)



Hi Martina - still an excellent function (I'm using R2013b) and thank you for updating it with my earlier suggested edit.

I'm trying to prepare a bar chart in black & white as required by a journal, and the solution here

reports an error:

Error using specgraph.barseries/get
The name 'paperpositionmode' is not an accessible property for an
instance of class 'barseries'.

Error in applyhatch_plusC (line 82)
oldppmode = get(h,'paperpositionmode');

...which I presume arises because of the way barwitherr generates the plot associated with the handle h.

I know it's not a fault in your code, but do you have any ideas how we could replace a colour with a hatching or shading pattern?



Any chance you could add an option to control the errorbar tick width, as this code used to do before Matlab 2014b kicked in:


Martina Callaghan

Now updated for 2014b - thanks Jiri for the linke.


As mentioned by others, error bars don't show properly on the new 2014b...


Great submission - very useful! The instructions are pretty clear as well.

Martina Callaghan

Hi WH,

I do not know why it wouldn't work in 2014b. Something similar was reported for 2013b though it worked in previous versions and in 2014a. I do not use 2014b so haven't tested. Perhaps a Matlab issue that will be ironed out.


This is a very useful script. Thank you!
However, I can get it to work in Matlab 2014a, but it doesn't work in Matlab 2014b trial version. The bars display properly but the error bars didn't. Do you know what the problem is? Thank you!


Thanks for your quick response. The color of both bars change together to red or green.
for example:

Martina Callaghan

Hi Parto,

For example:
h = barwitherr(randn(3,4), randn(3,4));
set(h(1), 'FaceColor','r')
set(h(2), 'FaceColor','g')

The first parameter will be red and the second parameter will be green.


Thank you very much for this useful matlab file. I just wanted to know how I can modify each bar separately, for example color?


Thank you! Works a charm!

Feifei Zhou


Nice and clean output. But, something fishy going on with Matlab R2013b. Even the example

y = randn(3,4);
errY = 0.1.*y;
h = barwitherr(errY, y);

spits out error

Error using errorbar (line 74)
X, Y and error bars must all be the same length

Error in barwitherr (line 126)
hErrorbar(col) = errorbar(mean(x,1), values(xOrder,col), lowerErrors(xOrder,col),
upperErrors(xOrder, col), '.k');

With earlier releases barwitherr.m seemed to work fine, and the very latest R2014a works as well, so probably some minor changes/bugs in Matlab internal functions..


Thank you very much! This is a very good extra. It is nice from you :)

Martina Callaghan

Hi Clare, yes, you can change the line width via:
[hBox hErr] = barwitherr(errY, y);
set(hErr(:), 'LineWidth', 2)


Very useful submission.
Is it possible to change the line width of the error bars?


Just got it to do it with the plot editor. all good.


Really helpful function, thanks! Is there any way to get it to plot a horizontal bar graph? I tried using the "rotate" function but it comes up the error "H must contain axes children only".


Martina Callaghan

Hi Cui, use asymmetric error bars (example in header) and set one error to 0.


I only want to plot the above half errorbar, how can I do with this function? Thanks very much.




Charles Collin

Very nice function. I changed the last bit (starting at line 107) like so to get rid of the dot in the middle of the error bar.

if nRows > 1
for col = 1:nCols
% Extract the x location data needed for the errorbar plots:
x = get(get(,'children'),'xdata');
% Use the mean x values to call the standard errorbar fn; the
% errorbars will now be centred on each bar; these are in ascending
% order so use xOrder to ensure y values and errors are too:
ebhandle = errorbar(mean(x,1),values(xOrder,col),lowerErrors(xOrder,col), upperErrors(xOrder, col), '.k');
set(ebhandle, 'Marker', 'none');

x = get(get(,'children'),'xdata');
ebhandle = errorbar(mean(x,1),values,errors,'.k');
set(ebhandle, 'Marker', 'none');


Cherkasov Nikolay

Unfortunately it does not work when one deals with the only group. Even the modified built-in example does not work ( y = randn(1,4); errY = zeros(1,4,2); errY(:,:,1) = 0.1.*y; errY(:,:,2) = 0.2.*y; barwitherr(errY, y); )
In order to solve this problem, line 118 should be modified to provide errors more explicitly - like this

Cherkasov Nikolay

Unfortunately it does not work when one deals with the only group. Even the modified built-in example does not work ( y = randn(1,4); errY = zeros(1,4,2); errY(:,:,1) = 0.1.*y; errY(:,:,2) = 0.2.*y; barwitherr(errY, y); )
In order to solve this problem, line 118 should be modified to provide errors more explicitly - like this

Martina Callaghan

Mossi, see the help entry for the file and the help entry for bar (dictates what kind of plots can be created).

You appear to have four parameters in three conditions. So, your data (y) and errors (errY) should each be held in a 3x4 matrix.
h = barwitherr(errY, y);

Use the handles "h" to tailor figure properties/appearance.


Thank you so much for the useful function. I could not create a special plot though. Here is the link to the plot picture:

I have created this plot in Excel but could not use Matlab to do it. Could you please guide me on how to use your function for plotting this?


Very useful function - I added a line to return the handle to the plot, so that existing commands from Matlab's "bar" can still be used with barwitherr:

> = bar(varargin{:}); % standard implementation of bar fn
>hold on

h =

and then change the function line at the top of the program to:

function h = barwitherr(errors,varargin)

You can then use things like


in your code that calls barwitherr, exactly as you would with calls to 'bar'.



Thanks for the program. Aurélien, nice addition, I modified your code a little to allow for different colors for multiple parameters in each group:

edge = [.4 .4 .4;.4 .4 .4;.4 .4 .4];
face = [0 1 0;0 0 1;1 0 0];
for n=1:length( %set colors

Aurélien BERTIN

I've added the following nice things to change color and bar size :
After line " = bar(varargin{:}); % standard implementation of bar fn":
for n=1:length(
set(,'edgecolor',[.4 .4 .4],'facecolor',[1 0.6 0.2]);
Colors can be even changed for a specified n.

After "hold off":
for n=1:length(h)
clear hh
x = get(hh(2),'xdata');
w = .1; % Horizontal lines width
x(4:9:end) = x(1:9:end)-w/2;
x(7:9:end) = x(1:9:end)-w/2;
x(5:9:end) = x(1:9:end)+w/2;
x(8:9:end) = x(1:9:end)+w/2;

It changes the width, and the aspect of the error bar line. With tha, you should also add an "end" after, the hold off being non longer the termination.

Anyway, very nice program!




Brendan Floyd

Simple and works well. Nice job.

Don Vaughn

Simple. Quick. Easy. Exactly what I was looking for


Works great for me, thanks!

Martina Callaghan

Asymmetric errors on 1D/2D data now working.


The asymmetric errors seem to work only with grouped/2D data

Martina Callaghan

The other options I came across were barerror #9377 & barweb #10803 as noted earlier. They were too complex for what I wanted. This submission is not an extension of any other hence no reference. It is something I find useful and have submitted in case others would too. If not of use, no problem.

Bolu Ajiboye

You stated that you came across other error bar scripts (like barweb, which has been around at least 6 years) but completely failed to acknowledge them.

Martina Callaghan

I have just gotten around to updating this so that it can be called with asymmetric error bars. Add an extra dimension to the erros so as to specify the upper and lower in each. Hope this helps.

sinoTrinity Liu

The errors are symmetric. How can I add asymmetric errors?

Quoc Viet Hung Nguyen

Martina Callaghan

The ones I came across (barerror #9377 & barweb #10803) are much more complex. With complexity came the need for extra parameters and less user control.
This submission is just a basic extension of MatLab's bar and errorbar functions, which are cited!
I don't have the time to go through all of the other versions to compare. If you do, feel free to post how you get on.

Zachary Danziger

Sorry, maybe its easier to search for files with file names instead of file IDs:


Zachary Danziger

What is the relevant difference between this code and submission #24718 specifically (or generally submissions #27387, #25613, #9377, or #9541)?

This is not a critique specific to this code, which is probably fine, but is there some way to reach a consensus on which of these functions is best? Or perhaps merge these submissions, or create a new umbrella submission for all of these? At any rate, the author should cite some of these predecessors.

MATLAB Release Compatibility
Created with R2010b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired: superbar

Community Treasure Hunt

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

Start Hunting!