File Exchange

image thumbnail


version (478 KB) by Kelly Kearney
Plot one or more lines with a shaded boundary (can represent error, confidence intervals, etc).


Updated 15 Jun 2020

From GitHub

View Version History

View license on GitHub

Editor's Note: This file was selected as MATLAB Central Pick of the Week

This function combines line and patch objects to create a "bounded line". This can be useful when plotting lines with error bounds/confidence intervals/etc.

For more details, including installation instructions, syntax, and examples, please see the README file included in this document (also visible via the GitHub link).

Cite As

Kelly Kearney (2021). boundedline.m (, GitHub. Retrieved .

Comments and Ratings (137)



goood job!

Simone Perazzolo

Overly complicated to run. Consider lump functions.

loai taouzlak

Mads Jensen

Alvince Pongos

If I take the log of the x-axis, boundedline() fails to draw a shaded boundary. Example
x = linspace(0, 2*pi, 50);
y1 = sin(x);
y2 = cos(x);
e1 = rand(size(y1))*.5+.5;
e2 = [.25 .5];
boundedline(log(x), y3, e3, 'alpha');

Pablo Trucco


Great function, thank you so much!

Abdelrahman Rayan

Christine Chen

Hello! I am working with timeseries data where the error bounds at a given time will overlap with the error bounds of another given time. When I use this function, these areas of overlap do not appear, leading to a very patchwork-like looking shaded area for the error bounds. Would anyone be willing to assist me with this issue? Sincerely, a desperate PhD student!

Ryan Tumminello

mingyu xiao

Serkan Guler

Great function, thanks.

Amneh Alshawabka

Brilliant Work, thank you very much :)

Noah Stanton

AHH nvm, found it in the folder... My bad!

Cuiqi Zhang

vaibhav singh

can anyone help with the error subscripted assignment dimension mismatch.

Error in Fig_1a (line 64)
[r,h(c)]= boundedline(x,cum_regret,10,['-',color(c)]);

Nandan Pandit

Excellent work, easy to use. highly recommend.

Pau Packard

John Hernandez

This is great! The only issue I have is that when I save the figures to PDF and put them into adobe illustrator, the bounding width (standard error) is made up of a ton of triangles. The borders of these triangles show up as white lines within the bounded line area. Is there any way to get rid of these? There may be a quick and easy fix, but I have not figured out how. Thanks!

Michal Szkup

Hao Lu

Mustapha Bennai

jon erickson

Xiao Chang

Sarah Blum

Beautiful function, thank you very much!
For everyone who is experiencing this error in inpaint_nans():
Error using .*
Sparse single array arithmetic operations are not supported.

It can be fixed by converting the inputs to double:

Sophia Feng

Daniel Seara

For those who wanted to change the marker size or anything like that (as I did), the key is to use the line figure handle that is output. For example:

[hl, ~] = boundedline(x, y, err, '.');
hl.MarkerSize = 20;

Only gave 4 stars for not being able to do that in one line. Otherwise perfect!


Hi, Is it possible to only plot standard deviation (e), without the mean line (y).


Hi Kelly. Thank you very much for the function. Like Maulik Shah, I wonder if there s a way to change the "markersize" Thank you

Cristian Villalobos

Can i use this with nans?

Jeongho Kim

Maulik Shah

Excellent utility! Is there a way to have a control on the marker size?

Eric Carruth


Essential tool! Is it possible for higher and lower bounds to be set separately? I rarely work with evenly distribute data and would like to show percentiles.


7 Oct 2011

excellent work.
if anybody else wants to avoid the patches appear in the legend simply add the following code after line 314.


this does the trick.

It should be in line 351.

Hein de Hoop


This seems to be a very useful function. Unfortunately, when I try to use the boundedline command using the following input parameters
X = 1x4100 double containing x-axis points
Y = 1x4100 single containing y-values
S = 4100x1 single containing for every value of y the SD across all participants contributing towards this y-value
h1=boundedline(X, Y, S, '-rx', 'nan', 'fill');
I get the error
"Error using *
MTIMES (*) is not supported for one sparse argument and one single argument.

Error in inpaint_nans (line 394)

Error in boundedline>calcpatch (line 451)
yp{ii} = inpaint_nans(yp{ii}', 4);

Error in boundedline (line 319)
[xp{iln}, yp{iln}] = calcpatch(plotdata{iln,1}, plotdata{iln,2}, isvert, plotdata{iln,6}, plotdata{iln,7}, nanflag);
The size(S,2) == 1, meaning according to the help that "the bounds will be symmetrical on both sides of the lines" and size(S,3) == 1, meaning "the same bounds will be applied to all lines described by the preceding x-y arrays", which is what we wanted to achieve. If we invert S to S' we get the same error. Can anyone help what this error means and how to avoid it?
Thank you in advance!


Yongjun Wang

Kelly Kearney


I've just updated this entry to include slightly better README files, describing installation and usage along with a few examples. Full syntax details are (and have always been) available via the function headers, accessible via the help command. You don't need to merge the files; just make sure to add the indicated folders to your Matlab path.


I am having trouble using it. There is no proper read me file. If I use boundedline function folder then the error is
Undefined function or variable 'inpaint_nans'.
If I merge all the files in folder, then it doesn't plot anything.
Can you please help.

amanda paulson


Kelly Kearney

@Maite Munoz,

I think it would be easier to preprocess your data rather than to modify the boundedline function. The stairs function makes this pretty easy; it can return the coordinates of the line object that it plots. Here's an example comparing an errorbar plot, boundedline plot, and stairs-style boundedline plot:

x = linspace(0,4*pi,40);
y = sin(x);
ci = rand(size(y))*0.3;



[xx, yy] = stairs(x,y);
[~,cici] = stairs(x,ci);


Maite Munoz

Hi, I am using this function but I would like to plot my result as a stairs graph instead of lineal (
Since I do not know much about matlab, I do not know how to start... I guess I need to modify this part of the code?
nline = size(plotdata,1);
[xl, yl, xp, yp, marker, lnsty, lncol, ptchcol, alpha] = deal(cell(nline,1));

for iln = 1:nline
xl{iln} = plotdata{iln,1};
yl{iln} = plotdata{iln,2};
% if isvert
% xp{iln} = [plotdata{iln,1} fliplr(plotdata{iln,1})];
% yp{iln} = [plotdata{iln,6} fliplr(plotdata{iln,7})];
% else
% xp{iln} = [plotdata{iln,6} fliplr(plotdata{iln,7})];
% yp{iln} = [plotdata{iln,2} fliplr(plotdata{iln,2})];
% end

[xp{iln}, yp{iln}] = calcpatch(plotdata{iln,1}, plotdata{iln,2}, isvert, plotdata{iln,6}, plotdata{iln,7}, nanflag);

marker{iln} = plotdata{iln,3};
lnsty{iln} = plotdata{iln,4};

if usealpha
lncol{iln} = plotdata{iln,5};
ptchcol{iln} = plotdata{iln,5};
alpha{iln} = trans;
lncol{iln} = plotdata{iln,5};
ptchcol{iln} = interp1([0 1], [1 1 1; lncol{iln}], trans);
alpha{iln} = 1;

any hint?

Jacob Nadel


Lijun Chen


Alexandra List

Nevermind--path conflict! It works beautifully :)

Alexandra List

Hi, I've used this great function before. I am now using Matlab 2016b, and it's throwing an error that I did not get before, even if I use your example. See below:

>> x = linspace(0, 2*pi, 50);
y1 = sin(x);
y2 = cos(x);
e1 = rand(size(y1))*.5+.5;
e2 = [.25 .5];

ax(1) = subplot(2,2,1);
[l,p] = boundedline(x, y1, e1, '-b*', x, y2, e2, '--ro');
title('Opaque bounds, with outline');

Error using unique>uniqueR2012a (line 271)
Input A must be a matrix in the 'rows' case.

Error in unique (line 147)
[varargout{1:nlhs}] = uniqueR2012a(varargin{1},logical(flaginds(1:5)));

Error in inpaint_nans (line 384)

Error in boundedline>calcpatch (line 450)
xp{ii} = inpaint_nans(xp{ii}', 4);

Error in boundedline (line 319)
[xp{iln}, yp{iln}] = calcpatch(plotdata{iln,1}, plotdata{iln,2}, isvert, plotdata{iln,6}, plotdata{iln,7}, nanflag);


Yongqiang Zhou

very cool.

hamid lessani


easily can be edited later by AI

Dene Farrell

Thanks for this cool function!

@andy this is a well known problem with Matlab versions 2014b+.

Only Mathworks can fix it, but they insist that it doesn't exist (?!).

Here is a workaround:


I like it!
Praise for the developers!

Julian Rüdiger

Hi! Thanks for this great code. I want to plot concentrations on the y-axis and time on the x-axis. I only got a problem using this code while plotting decimal daytime (e.g. 0.57 for 1pm) on the x-axis instead of a duration in seconds or so (I got a data point every 0.5 s). With the decimal daytime the shaded error area isn't shown properly and forms shaded areas all over the plot. Did anybody expierience something like that?

adam taylor

Great job, very usable. It'd be nice to pass line specifiers/parameters to outlinebounds to soften the outlines when using very transparent patches, can look noisy with multiple lines that fall close together

Kelly Kearney

@Hannah Nissan

There's nothing special in this function that should affect saving or printing (no listeners or figure resize functions or anything like that); it produces simple lines and patches. If this really only happens for you with boundedline plots (as opposed to other plots with patches and lines), can you enter this as an issue on GitHub, with operating system info as well as exact commands to reproduce the problem?

Hannah Nissan

The graphs are great, but for some reason Matlab hangs when I try to save the figures. It doesn't do this with figures created using other plotting commands. I'm running Matlab 2014a.

Any suggestions for a workaround?



Xiaodan Sun

Thank you very much!

Kiran Karra


In newer versions of Matlab (2015b vs. 2013s), when you 'ungroup' a boundedline plot in PowerPoint the shaded fill is several smaller polygons that collectively create the full shaded area. In previous versions it was a single shape. Does anyone know how to fix this?



Nice program, although it seems that the CI or stderr need to be calculated by the users.
About the line width question raised by Omar Choudary:
I modified the program a little bit by adding the following codes into the program:
[found, width, varargin] = parseparam(varargin, 'linewidth');
if ~found
width = 1;

hl(iln) = line(xl{iln}, yl{iln}, 'marker', marker{iln}, 'linestyle', lnsty{iln}, 'color', lncol{iln},'linewidth',width, 'parent', has);

So when I use this nice program I would type
boundedline(X,Y,CI, 'linewidth', 2);

Kelly Kearney


Yes, just use the option 'cmap' input to specify any color(s) you want.


Is it possible to specify custom colors for the lines, i.e., not the pre-specified color codes from linespec?

Vladimir Calderón

P. Agbesi Fiave

Jie Xi

James Ratti

@Alex Perrone,

Thank you for the help, that worked great! I don't think I would've considered editing the line or patch properties. After making that edit, I noticed that with a couple extra lines of code you wont have to separately pre-define the axes or change its visibility after calling boundedline, and it will prevent the axis from popping up when boundedline is called iteratively in a loop.

Here's my version of the edited code you posted:

% axes(hax); % do not call (edited by Alex P)
hold(hax, 'on'); % edit by Alex P
set(hax, 'visible', 'off'); % prevents axes taking focus (added by James R)

for iln = 1:nline
hp(iln) = patch(xp{iln}, yp{iln},...
'facealpha', alpha{iln},...
'edgecolor', 'none',...
'Parent', hax); % added by Alex P

for iln = 1:nline
hl(iln) = line(xl{iln}, yl{iln},...
'marker', marker{iln},...
'linestyle', lnsty{iln},...
'color', lncol{iln},...
'Parent', hax); % added by Alex P
set(hax, 'visible', 'on'); % makes axes visible when called later (added by James R)

Then, the example I gave works without having to deal with individual axes outside of the function:
x = 1:10;
y(1,:) = x + rand(1, 10);
y(2,:) = 2*x + rand(1, 10);
boundary = 2 * ones(1, 10);

h = figure('visible', 'off');
for i = 1:size(y,1)
boundedline(x, y(i,:), boundary);

% Now turn it on.
set(h, 'Visible', 'on');

I'm creating multiple figures and adding plots to each through dozens of iterations, so this format was simpler for me by allowing me to only deal with figure handles and properties throughout the rest of my script.

Kelly, I'm not sure how to properly test it, but based off the runtimes for this example script, these edits make loops with borderline within them 10-11% faster.

Kelly Kearney

@Alex (and James),

Yes, the way I was calling targeting the axis (via axes(), rather than just setting the Parent) was causing the extra side effect of bringing the axis into focus (and this is true regardless of whether he passed the optional axis handle). I've updated the code as Alex suggested to avoid this behavior (and also to avoid changing the hold status of the axis; that's not necessary). New version will be uploaded shortly (as soon as I resolve a bit of a technical issue with my git repos) , and will also include new NaN behavior. Thanks for the feedback!

Alex Perrone

@James Ratti,

I remarked on this below, though it was nonsensical because I answered a question to myself, but for some reason the question I tried to post never showed up.

Anyway, my question was about passing axes handles to boundedline. My answer (below from 23 Jan 2016) was essentially that I had to set 'Parent' to hax in the boundedline function for the patch and line commands, in and around line 340 in the current version.

In addition, the axes(hax) line also makes the figure show up, and I don't think it is needed anyway.

Specifically, here are lines 336-345 in the CURRENT version of boundedline

hold all;

for iln = 1:nline
hp(iln) = patch(xp{iln}, yp{iln}, ptchcol{iln}, 'facealpha', alpha{iln}, 'edgecolor', 'none');

for iln = 1:nline
hl(iln) = line(xl{iln}, yl{iln}, 'marker', marker{iln}, 'linestyle', lnsty{iln}, 'color', lncol{iln});

I changed these lines to:

%axes(hax); % do not call
hold(hax, 'on'); % only need to hold hax on, not all

for iln = 1:nline
hp(iln) = patch(xp{iln}, yp{iln}, ptchcol{iln}, ...
'facealpha', alpha{iln}, 'edgecolor', 'none', ...
'Parent', hax); % alex added 'Parent', hax

for iln = 1:nline
hl(iln) = line(xl{iln}, yl{iln}, 'marker', marker{iln}, ...
'linestyle', lnsty{iln}, 'color', lncol{iln}, ...
'Parent', hax);

Then, here is your example, hope this works for you.

x = 1:10;
y = x + rand(1, 10);
boundary = 2 * ones(1, 10);

h2 = figure('visible', 'off');
ax = axes('Parent', h2, 'Visible', 'off');
boundedline(x, y, boundary, ax);

% Now turn it on.
set(ax, 'Visible', 'on');
set(h2, 'Visible', 'on');

To summarize, I think the problem you had was twofold:
(1) you were not passing in the axes handles to boundedline function
(2) the way the boundedline function treats handles needs to be changed,
at least I think it does for your example and it did for my GUI as well
since it was not correctly plotting things on the axes handles I was
giving it where the axes handles were embedded in complex GUI (thus I
had to specify 'Parent' as above myself).

Kelly, I'm not sure if the change I made should be incorporated into boundedline, but it's what I had to do to make it work.

James Ratti

Thank you for posting this! This function has solved so many headaches for me, but I'm running into an issue where it overwrites the visibility property of the figures I use it in. My script is creating boundedlines across multiple figures within a loop and I'd like to keep their visibility suppressed to prevent them from popping up with each plot/iteration and decrease the overall processing time.

Here's an example:

x = 1:10;
y = x + rand(1, 10);
boundary = 2 * ones(1, 10);

h1=figure('visible', 'off');

h2=figure('visible', 'off');
boundedline(x, y, boundary);

Is there an easy way to prevent or work around this? Any help would be greatly appreciated!

Alex Perrone

@Kelly Kearney @Ian Craig @Benjamin Pittman-Polletta @Bass @Eelke Spaak,

I have added an issue to the github repository for what I take to be the most common/useful case of handling NaNs and what desired output should look like. Unless Kelly prefers otherwise, please comment on the Issue on github so it is more easily tracked. I hope it reflects what others have mentioned. For myself, it is currently the case I need to work for this function.

Kelly Kearney


It's difficult to know exactly what's going on there without an example. I like using export_fig (from the FEX) rather than print/saveas/etc to save to file; it generally preserves on-screen appearance better. You may also want to play around with stacking of objects (see uistack) to solve the line hiding issue (the lines are stacked on top of the patches by default, but a subsequent adjustment may have rearranged things).

Thomas Leirvik


First: thanks for a great function!

I'm trying to save the figure I make with boundedline as a .pdf or a .epsc using the command:




However, the output is not good:
1) in the pdf file, the left and rigth margins are cut off, so the y-axis does not show, as well as the last observations on the x-axis.

2) In the .eps file, one of the lines plotted does not show at all. It's like is behind all the others (the plot from observation 1 to 2 shows, as it is above the bounded lines. from observation 2 it 'goes behind'.

Any comments to fix this is appreciated!


Kelly Kearney


You could use a two-axis setup, similar to plotyy, to get that effect. Here's an example, with the first two lines using the bottom x axis and the third one using the top x axis:

y = linspace(0, 2*pi, 100)';
x = [sin(y) cos(y)+0.5 sin(y)*100];
e = permute(ones(100,1)* [1 2 3], [1 3 2]);
iax = [1 1 2]; % axis to use for each line

ax(1) = axes('box', 'off', 'xaxisloc', 'bottom');
ax(2) = axes('position', get(ax(1), 'position'), ...
'color', 'none', ...
'ytick', '', ...
'xaxisloc', 'top');
linkaxes(ax, 'y');

for ii = 1:size(x,2)
[hl(ii), hp(ii)] = boundedline(x(:,ii), y, e(:,:,ii), ...
ax(iax(ii)), 'cmap', ax(1).ColorOrder(ii,:), ...
'orientation', 'horiz', 'alpha');
ax(1).YLim = [0 2*pi];


Is there a neat way to use this great function but have 2 different x axis scales? I am using it with 'horiz' as my dependent variable is on the x axis, but I would like to display 2 different datasets on the same graph. they have y axis in common but not x axis.
thanks in advance for any help



Many thanks, got it to work thanks to your example.

Kelly Kearney


For a linear model, you'd calculate the bounds by subtracting predicted values from predicted confidence interval values. Here's a quick example:

load carbig
mdl = fitlm(Horsepower,MPG);

xnew = linspace(10, 250, 100)';
[ynew, ci] = predict(mdl, xnew);

b = [ynew-ci(:,1) ci(:,2)-ynew];

boundedline(xnew, ynew, b);


Many thanks for sharing first of all.

I'm having some trouble understanding the inputs for this command, especially "b".
I have a linear regression and would like to display the 95% CI, extrapolated outside the measuring range. I have run fitlm, and coefTest on my data but don't quite understand what the input for boundedline needs to be. Any help (especially if you can share examples) would be appreciated, can't claim to be an expert.

Alex Perrone

@Alex (responding to myself) In the boundedline function set the 'Parent' property in the patch and line commands manually: patch(..., 'Parent', hax);

Dan K

Harald Hentschke

Works beautifully, thanks a lot, also for the updates!

Mark Hines

Superb! Thanks a million for the quick response (and for the file). Many headaches relieved.

Kelly Kearney


That error means you haven't added the code to your Matlab path; the boundedline and Inpaint_nans folders both need to be on your path before you can use this function. Search the documentation for "search path" for instructions on doing this.

Mark Hines

Help with this would be great. I am calculating my x, y1 and y2 in Matlab with the results being typically around 110x1 (double), representing confidence intervals about a mean, over time). I get the following error: "??? Undefined function or method 'boundedline' for input arguments of type 'double'".

Xolile Ncipha

I'm a student working to build my capacity with matlab. I want to plot shaded error bar or boundedline graphs for vertical profiles of CO2. When I'm using the Confplot or Shaded Error Bar codes, I don't get error messages. However the vertical profile I get doesn't have the shaded boundaries. I'm using the STDDEV values as the error margin or limit. What can be causing this?

Kelly Kearney


Could you please submit this feature request via the Issues page on GitHub? (Follow the link below the download button in the upper right).

I'm willing to try to implement this feature, but need more examples of the expected output under different situations (NaN in line data only? In bounds data only? In one side of the bounds and not the other?) Do you want to see a gap in the patch, or just the line? Etc.

Ian Craig

I've been looking for a function that would both make a bounded line like this AND behave as @Benjamin Pittman-Polletta suggests below, skipping NaN values altogether rather than inpainting. However, it seems that the version that inserted at line 268 is different than the current version, and inserting at that line seems to make things very unhappy, so I'm not quite sure where to put it in the current version.

Therefore, I am making a feature request to allow this behavior with a switch, so that one could choose between inpainting and skipping.

Otherwise, very beautifully written.

Lekshmi Dharmarajan

Lovely thanks!

Alberto Jr

So how do you work this thing? I am confused. Sorry, barely new at Matlab and just wondering how would a general code works by breaking it down.

Kelly Kearney


That error usually indicates that Matlab can't find the function file... Did you make sure to add both the boundedline and Inpaint_nans folders to your path before trying to call the function?


can someone check the example, it says "Undefined function 'boundedline' for input arguments of type 'double'" The issue is at the first use of the function, "[l,p] = boundedline(x, y1, e1, '-b*', x, y2, e2, '--ro');" it doesn't work with doubles? is there an example that works so I can test functionality?
Please help

Sevasti Modestou

@ Aditya

Thanks for the heads up!


@ Sevasti Modestou

If you are using MATLAB 2014, it is most likely a problem with MATLAB while exporting to eps. 2015a fixes it. I and many others have had issues with the eps export in 2014. I came to know of this from another thread where people were trying to export to eps to embed images in LaTeX.

Sevasti Modestou

This function is fantastic! I really appreciate the time and effort, it makes my life so much easier!

I have an issue when I save as .eps and open in Illustrator. The shaded area doesn't match up to the lines around it - usually it appears shifted downwards a small amount but it may also be shifting slightly to the side, probably the left. Any ideas? Thanks!

That fixed it, thanks!

Kelly Kearney


My guess is that OpenGL is the culprit. For pre-2014b, see workarounds in the documentation under Figure Properties > Renderer. This is a Matlab bug, not unique to this function. The problem should be resolved with the new handle graphics (R2014b+).

Thanks for this great function! I am having some problems, though, with combining this function and a colorbar on the same figure when I use the 'alpha' option. For example, the following code for me produces a lot of gibberish numbers next to the colorbar:

x = linspace(0, 2*pi, 50);
y1 = sin(x);
y2 = cos(x);
boundedline(x, [y1;y2], rand(length(y1),2,2)*.5+.5, 'alpha');

Whereas there is no problem if I don't use 'alpha':

x = linspace(0, 2*pi, 50);
y1 = sin(x);
y2 = cos(x);
boundedline(x, [y1;y2], rand(length(y1),2,2)*.5+.5);

(Note: I know in this example there's no real need to have a colorbar anyway. For real purposes, though, I often make plots which have something like this [] on a subplot and a boundedline on another subplot; this becomes an issue then)

(Also note: I get the same problem when using shadedErrorBar.m)


Thanks for the submission! Made my day SO much easier!

To get boundedline to treat nans the same way 'plot' does - i.e., leaving a blank space above where the nans appear - I inserted the following code at line 268:

% Splitting lines w/ nans in them.

plotdata_supp = cell(0, 7);
is_nan = zeros(size(plotdata,1),1);

for k = 1:size(plotdata,1)

naninds = isnan(plotdata{k,1}) | isnan(plotdata{k,2});

if any(naninds)

is_nan(k) = 1;

notnaninds = [0 ~naninds 0];
notnanstarts = find(diff(notnaninds) == 1);
notnanends = find(diff(notnaninds) == -1) - 1;

nopolys = length(notnanstarts);

for l = 1:nopolys

poly_indices = notnanstarts(l):notnanends(l);

xdata = plotdata{k,1}(poly_indices);
ydata = plotdata{k,2}(poly_indices);
lodata = plotdata{k,6}(poly_indices);
hidata = plotdata{k,7}(poly_indices);

plotdata_supp = [plotdata_supp; {xdata ydata ... plotdata{k,3:5} lodata hidata}];




plotdata = [plotdata(~is_nan, :); plotdata_supp];

Pierre Mégevand

Irene Seco


Kelly Kearney


The cmap input option should allow you to specify the colors you want to use for the lines, so that you can maintain the correlation between line and patch. For example:

[hl,hp] = boundedline(1:10, rand(10,1), 0.1, 'cmap', [0.3 0.2 0.5]);
set(hl, 'linewidth', 3);

Line style, etc. still need to be modified after the fact; color is treated specially due to the link between line and patch that you point out.

Omar Choudary

Very nice script.

However, for my particular application (and perhaps for others), it would be very useful to allow the possibility of giving the line properties individually, as for plot. That is, I want to give something like:

boundedline(..., 'Color', [0.3 0.2 0.5]);
or boundedline(..., 'LineWidth', 3)

instead of the string format option (e.g. 'r-').

The advantage of that would be that I can have my own table of colors, line specs, etc. specific to each line I want to plot and I want to use that with your function to specify the properties in advance. Otherwise it is very difficult to change the color afterwards without making it totally uncorrelated (and useless) with the color of the patches you create.


Lovely function! makes pretty plots. Sadly I haven't yet found an easy way to save plots with these patches in a vectorized form. My two cents regarding NaNs. While I agree there is clearly some ambiguity as to what to do with NaNs. The complete lack of support is not consistent with the basic behavior of existing plotting functions like 'line.' Which one would like to seamlessly substitute for a function like this.
'Line' introduces a discontinuity at NaNs This implementation may be slightly more difficult with patches. But it has the benefit of both being consistent with the meaning of a NaN and very convenient for formatting plots (e.g. when the user desires to easily separate an otherwise contiguous line.)

Kelly Kearney


I intentionally did not include a workaround for NaN/Inf values in the bounds because it seems that everyone I've asked prefers a different method of dealing with these (drop the points, interpolate at those locations, substitute 0 for NaNs or a suitably large value for Infs, etc.). So instead, I leave it for the user to preprocess their data appropriately.

Eelke Spaak

Thanks for this great and simple submission. I have noticed one problem though, it cannot handle NaNs in the data. Matlab's plot() and line() simply ignore NaN values, but patch() does not draw anything when there are NaNs in the data.

To fix this, I added the following around line 313, right before the actual calls to line() and patch():

% remove nans
for k = 1:numel(xp)
naninds = isnan(xp{k}) | isnan(yp{k});
xp{k} = xp{k}(~naninds);
yp{k} = yp{k}(~naninds);

David McElroy

Great little submission.

I am having issues with the 'alpha' option. This file works fine on my work computer, but crashes matlab on my laptop and I am stuck overseas and desperate! Looking at the problems other users had with 'alpha' maybe it's something to do with opengl?


Ben Curtin

@Kelly - Thanks! I had no idea and will look into it some more.

Kelly Kearney


Unfortunately, the OpenGL renderer is the only one that supports transparency, but it does not support logarithmic axes (see, under "OpenGL vs. Other MATLAB Renderers"). If you need transparency, your best bet is probably to log-transform your data prior to plotting.

Ben Curtin

Thanks for writing this! I'm having an issue with the bounded line not being transparent when setting the x-axis to a log scale with:


I also have tried different opengl settings with no luck.

Chris Jones

Thank you, this is quite useful! I appreciate the transparency feature.

Ali Hummos

@ Kelly,
Thanks a million. I only had to switch off hardware accelerated opengl and the problem disappeared.
Basically, I only had to issue the command:
>>> opengl software
and it was fixed!

Kelly Kearney


My guess is that your OpenGL renderer is the culprit. I've gone through several computers in my Matlab-using time, including PCs and Macs, and always have issues of some sort with this (note that in my example screenshot, my axes box also goes missing... that's computer-specific). You can try some of the workarounds here:

Ali Hummos

Great work! It looks beautiful too.
Something happened however, I think when I updated to Matlab 2013, and now when I use the 'alpha' arugment the y axis line disappears!
Anyone had this issue??
Not sure how to resolve.


Daniel Lopes

Works like a charm! Great code.

Kelly Kearney

@Gideon and Martin,

There's nothing in this function preventing you from setting the axis to a log scale via 'xscale' and 'yscale' properties, assuming all your inputs lead to positive values for the boundaries (like NaNs and Infs, negative values displayed on a log scale will cause the bounds patch to disappear). If you are looking for something more complex than that, please send me an example and I'll look into it.

Martin Nors Pedersen

Great function - very useful

like Gideon Simpson i would to plot some of my data on log scale - is this possible using this function?

when i try the bounderies are same color as the line so it is difficult to distinquish what is the mean and what is the stdev :)

Gideon simpson

Works well, but is it possible to put one of the axes on a log scale?

Mohammed Alwesabi


excellent work.
if anybody else wants to avoid the patches appear in the legend simply add the following code after line 314.


this does the trick.



Felipe G. Nievinski

good job in pointing out advantages over several other similar entries on the FEX.


Awesome. It works perfectly on the screen.
The only problem for me is that the transparent color cannot be exported with vector graphics pdf. If opengl renderer is used, it will convert it to raster, which is not so desirable.



I experienced the following problem on my mashine with nVidia graphics:
When using the 'alpha' option the axes are overlayed. This a problem caused by the OpenGL rendering.
Workaround: activate software rendering by
opengl software;


This is a very useful function that does almost exactly what I was trying to do, and it should save me a lot of time. Thanks for making it!

I think, though, that it would be even more useful if you made two modifications:

1) The reference color of the bounded area should be set independently (as an RGB array), rather than being constrained to be a lighter shade of the corresponding line color. This would be particularly relevant for users preparing b&w figures for publication who, for example, might want to use two black lines and two different shades of grey for the bounded areas. The specific example I provided could of course be facilitated simply by allowing separate transparency parameters for each bounded area, but that still would not provide as much flexibility as some users might want.

2) The default behavior of 'legend' is to use shaded boxes that are the same colors as the bounded areas. Some users might prefer that the legend use lines of the same color and style as the corresponding data. It would be nice to have the option of using either. I believe this could be controlled from within boundedline.m by setting the 'IconDisplayStyle ' property of the 'LegendEntry' array of each patch to 'on' or 'off'.

Example code:

Also, there appears to be a bug (using R2007b): adding a legend to a figure that was made using the 'alpha' option results in no legend and no bounded areas.

Zachary Danziger

Nice file. I enjoy the flexibility.

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

Community Treasure Hunt

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

Start Hunting!