Is it possible to draw a line across all plots in a stackedplot?

figure;
chans = 10;
for subplotN=1:chans-1 %plot first set of time-series
x = 1:2841;
y(:,subplotN) = randn(2841,1)*50;
end
y(:,subplotN+1) = randn(1,2841)*1e6;
stackedplot(x,y)
Is it possible to draw vertical lines across all stackedplots like in the figure below?

 Accepted Answer

I am not sure if there is any direct option, but you can use annotation() to draw a line on the figure window such that it appears on the axes at correct locations. Following code shows an example
figure;
chans = 10;
for subplotN=1:chans-1 %plot first set of time-series
x = 1:2841;
y(:,subplotN) = randn(2841,1)*50;
end
y(:,subplotN+1) = randn(1,2841)*1e6;
s = stackedplot(x,y);
pos = s.Position;
xlims = s.xlim;
line_locations = [500 1000 1500 2000 2500];
line_locations_norm = interp1(xlims, cumsum(pos([1 3])), line_locations);
for i=1:numel(line_locations_norm)
annotation('line', ...
[line_locations_norm(i) line_locations_norm(i)], ...
[pos(2) pos(2)+pos(4)], ...
'Color', 'r', ...
'LineWidth', 1);
end

4 Comments

Thanks, that works! I modified slightly to stop the lines from going in to the bottom plot.
Do you know if it's possible to remove the white background, tickmarks and alter the tick labels like in the example image? This was much easier with subplot when I could access axis handles. Thank you for your time.
The stacked plot was recently introduced, and still, several options are not supported. For example, it is not possible to change the background color or make the axes invisible. I created a similar plot using subplots(). Try this
figure;
chans = 10;
for subplotN=1:chans-1 %plot first set of time-series
x = 1:2841;
y(:,subplotN) = randn(2841,1)*50;
end
y(:,subplotN+1) = randn(1,2841)*50;
labels = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
ax = gobjects(1, 10);
for i=1:10
ax(i) = subplot(10,1,i);
plot(x, y(:,i));
ax(i).Color = 'none';
ax(i).XAxis.Visible = 'off';
ax(i).YAxis.Visible = 'off';
ylabel(labels{i}, 'Visible', 'on');
ax(i).Position(4) = 0.07;
ax(i).XLim = [min(x) max(x)];
end
pos(1:3) = ax(10).Position(1:3);
pos(4) = sum(ax(1).Position([2 4])) - ax(10).Position(2);
xlims = ax(1).XLim;
line_locations = [500 1000 1500 2000 2500];
line_locations_norm = interp1(xlims, cumsum(pos([1 3])), line_locations);
for i=1:numel(line_locations_norm)
annotation('line', ...
[line_locations_norm(i) line_locations_norm(i)], ...
[pos(2) pos(2)+pos(4)], ...
'Color', 'r', ...
'LineWidth', 1);
end
Thanks Ameer! I was able to modify that approach to end up with the subplot I needed.

Sign in to comment.

More Answers (0)

Products

Release

R2019b

Community Treasure Hunt

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

Start Hunting!