Get from Ico-github-logo

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Highlights from

  • boundedline(varargin)
    BOUNDEDLINE Plot a line with shaded error/confidence bounds
  • catuneven(dim, padval, va...
    CATUNEVEN Concatenate unequally-sized arrays, padding with a value
  • inpaint_nans(A,method)
  • inpaint_nans_bc(A,method,...
  • outlinebounds(hl, hp)
    OUTLINEBOUNDS Outline the patch of a boundedline
  • singlepatch(varargin)
    SINGLEPATCH Concatenate patches to be plotted as one
  • methods_of_inpaint_nans.m
  • inpaint_nans_demo.m
    Surface Fit Artifact Removal
  • test_main.m
    Repair to an image with 50% random artifacts
  • inpaint_nans_demo_old.m
    Surface fit artifact removal
  • View all files
4.8 | 33 ratings Rate this file 226 Downloads (last 30 days) File Size: 420 KB File ID: #27485 Version: 1.4
image thumbnail



Kelly Kearney (view profile)


05 May 2010 (Updated )

Plot one or more lines with a shaded boundary (can represent error, confidence intervals, etc).

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

| Watch this File

File Information

Plot line(s) with error bounds/confidence intervals/etc. in Matlab


Confplot, Errorfill, and Shaded Error Bar inspired this file.

MATLAB release MATLAB 7.5 (R2007b)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (65)
16 Mar 2016 Jie Xi

Jie Xi (view profile)

10 Mar 2016 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.

Comment only
10 Mar 2016 Kelly Kearney

Kelly Kearney (view profile)

@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!

Comment only
10 Mar 2016 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.

Comment only
10 Mar 2016 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!

15 Feb 2016 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.

10 Feb 2016 Kelly Kearney

Kelly Kearney (view profile)


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).

Comment only
08 Feb 2016 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!


Comment only
30 Jan 2016 Kelly Kearney

Kelly Kearney (view profile)


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];

Comment only
29 Jan 2016 Anna

Anna (view profile)

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

Comment only
27 Jan 2016 photoinduced


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

Comment only
26 Jan 2016 Kelly Kearney

Kelly Kearney (view profile)


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);

Comment only
26 Jan 2016 photoinduced

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.

Comment only
23 Jan 2016 Alex Perrone

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

Comment only
03 Jan 2016 Dan K

Dan K (view profile)

16 Sep 2015 Harald Hentschke

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

31 Aug 2015 Mark Hines

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

Comment only
31 Aug 2015 Kelly Kearney

Kelly Kearney (view profile)


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.

Comment only
31 Aug 2015 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'".

18 Aug 2015 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?

Comment only
15 Aug 2015 Kelly Kearney

Kelly Kearney (view profile)


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.

Comment only
14 Aug 2015 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.

06 Aug 2015 Lekshmi Dharmarajan

Lovely thanks!

06 Jul 2015 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.

Comment only
09 Apr 2015 Kelly Kearney

Kelly Kearney (view profile)


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?

Comment only
09 Apr 2015 Dwight

Dwight (view profile)

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

Comment only
03 Apr 2015 Sevasti Modestou

@ Aditya

Thanks for the heads up!

Comment only
02 Apr 2015 Aditya

Aditya (view profile)

@ 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.

02 Apr 2015 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!

13 Jan 2015 Stephen Politzer-Ahles

That fixed it, thanks!

12 Jan 2015 Kelly Kearney

Kelly Kearney (view profile)


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+).

Comment only
12 Jan 2015 Stephen Politzer-Ahles

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)

03 Oct 2014 Stephen

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

15 Aug 2014 Benjamin Pittman-Polletta

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];

05 Aug 2014 Pierre M├ęgevand  
29 Apr 2014 Irene Seco  
25 Apr 2014 Katherine  
02 Feb 2014 Kelly Kearney

Kelly Kearney (view profile)


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.

Comment only
01 Feb 2014 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.

13 Jan 2014 Bass

Bass (view profile)

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.)

17 Dec 2013 Kelly Kearney

Kelly Kearney (view profile)


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.

Comment only
28 Nov 2013 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);

Comment only
21 Nov 2013 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?


Comment only
01 Nov 2013 Ben Curtin

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

Comment only
01 Nov 2013 Kelly Kearney

Kelly Kearney (view profile)


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.

Comment only
31 Oct 2013 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.

20 Oct 2013 Chris Jones

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

23 Sep 2013 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!

Comment only
17 Sep 2013 Kelly Kearney

Kelly Kearney (view profile)


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:

Comment only
12 Sep 2013 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.

02 Apr 2013 Warwick  
28 Feb 2013 Daniel Lopes

Daniel Lopes (view profile)

Works like a charm! Great code.

17 Feb 2013 Kelly Kearney

Kelly Kearney (view profile)

@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.

Comment only
15 Feb 2013 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 :)

20 May 2012 Gideon simpson

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

30 Jan 2012 Mohammed Alwesabi  
07 Oct 2011 dbgtjp

dbgtjp (view profile)

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.

07 Oct 2011 dbgtjp

dbgtjp (view profile)

26 Aug 2011 Vassilis Kehayas  
26 Mar 2011 Felipe G. Nievinski

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

Comment only
06 Jan 2011 Il

Il (view profile)

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.

11 Aug 2010 Alexander  
10 Aug 2010 Alexander

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;

Comment only
09 Jun 2010 Dylan

Dylan (view profile)

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.

19 May 2010 Zachary Danziger

Nice file. I enjoy the flexibility.

Comment only
30 Jan 2013 1.1

Added outlinebounds.m function to allow outlining of patch objects (can be useful to see overlap when using opaque bounds).

09 Jun 2014 1.2

Per user request, function now interpolates across NaNs in the boundary patches.

10 Jul 2014 1.3

Updated for R2014b graphics

29 Mar 2016 1.4

Linked entry to GitHub

Contact us