How can I add error bars to a stacked plot?

11 views (last 30 days)
Trying to add errorbars to a stacked plot? Seems there's no way to do this which is a shame as I very much like the way a stacked plot presents the data by comparing 3 variables with distinctly different y-axes against my x variable.
figure()
s = stackedplot(dist, stack, "DisplayLabels", ylabels); % stacked plot
xlabel('Distance from Springhead (m)')
title('Carbonate Chemistry with Distance Downstream')
grid on

Accepted Answer

Star Strider
Star Strider on 24 Feb 2023
A (slightly tortured) tiledlayout array might work —
x = 0:0.5:10;
y = randn(3,numel(x));
err = randn(3,numel(x))/5;
figure
tiledlayout(3,1)
nexttile
errorbar(x, y(1,:), err(1,:))
Ax = gca;
Ax.XAxis.Visible = 'off';
% axis('padded')
nexttile
errorbar(x, y(2,:), err(2,:))
Ax = gca;
Ax.XAxis.Visible = 'off';
axis('padded')
nexttile
errorbar(x, y(3,:), err(3,:))
Ax = gca;
xt = Ax.XTick;
Ax.XAxis.Visible = 'off';
% axis('padded')
hold on
plot(xlim, [1 1]*min(ylim), '-k')
plot([1;1]*xt, [zeros(size(xt)); ones(size(xt))*0.07*diff(ylim)]+min(ylim),'-k')
hold off
text(xt, ones(size(xt))*min(ylim), string(xt), 'Horiz','center', 'Vert','top')
.
  3 Comments
Les Beckham
Les Beckham on 24 Feb 2023
Note that you can adjust the spacing between the "stacked" plots to tweak how it looks (experiment with it).
Also, you should use (or not use) axis('padded') on all three tiles.
x = 0:0.5:10;
y = randn(3,numel(x));
err = randn(3,numel(x))/5;
figure
tiledlayout(3,1, 'TileSpacing', 'tight') %<<< or 'compact' or 'none' (but 'none' looks bad here)
nexttile
errorbar(x, y(1,:), err(1,:))
Ax = gca;
Ax.XAxis.Visible = 'off';
grid on
% axis('padded')
nexttile
errorbar(x, y(2,:), err(2,:))
Ax = gca;
Ax.XAxis.Visible = 'off';
% axis('padded')
grid on
nexttile
errorbar(x, y(3,:), err(3,:))
Ax = gca;
xt = Ax.XTick;
Ax.XAxis.Visible = 'off';
% axis('padded')
hold on
plot(xlim, [1 1]*min(ylim), '-k')
plot([1;1]*xt, [zeros(size(xt)); ones(size(xt))*0.07*diff(ylim)]+min(ylim),'-k')
hold off
text(xt, ones(size(xt))*min(ylim), string(xt), 'Horiz','center', 'Vert','top')
grid on

Sign in to comment.

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!