Search code examples
matlabplotfillarea

MATLAB fill area between lines


I'm trying to do something similar to what's outlined in this post: MATLAB, Filling in the area between two sets of data, lines in one figure but running into a roadblock. I'm trying to shade the area of a graph that represents the mean +/- standard deviation. The variable definitions are a bit complicated but it boils down to this code, and when plotted without shading, I get the screenshot below:

x = linspace(0, 100, 101)';    
mean = torqueRnormMean(:,1);
meanPlusSTD = torqueRnormMean(:,1) + torqueRnormStd(:,1);
meanMinusSTD = torqueRnormMean(:,1) - torqueRnormStd(:,1);
plot(x, mean, 'k', 'LineWidth', 2)
plot(x, meanPlusSTD, 'k--')
plot(x, meanMinusSTD, 'k--')

mean and std

But when I try to implement shading just on the lower half of the graph (between mean and meanMinusSTD) by adding the code below, I get a plot that looks like this:

fill( [x fliplr(x)],  [mean fliplr(meanMinusSTD)], 'y', 'LineStyle','--');

shaded

It's obviously not shading the correct area of the graph, and new near-horizontal lines are being created close to 0 that are messing with the shading.

Any thoughts? I'm stumped.


Solution

  • It turned out to be a column vs row vector issue. For some reason using the fill method above with flipud with the original column vectors doesn't work, but transposing the original variables then using fliplr does. Go figure. Here's the code in case it helps someone else:

    x = linspace(0,100, 101);
    mean = torqueRnormMean(:,DOF)';
    meanPlusSTD = torqueRnormMean(:,DOF)' + torqueRnormStd(:,DOF)';
    meanMinusSTD = torqueRnormMean(:,DOF)' - torqueRnormStd(:,DOF)';
    fill( [x fliplr(x)],  [meanPlusSTD fliplr(meanMinusSTD)], 'k');
    alpha(.25);
    plot(x, mean, 'k', 'LineWidth', 2)
    plot(x, meanPlusSTD, 'k')
    plot(x, meanMinusSTD, 'k')
    

    Note that I removed the dotted line and just used thin vs. thick lines to denote standard deviation and mean. I did this because the line style was inconsistent. This code is in a loop where DOF runs from 1:9, and in some of the subplots both std curves would be dashed and in some just the top or bottom. It didn't matter enough to me to have them dashed so I kept it simple. Now this is an example of the graph I get:

    enter image description here