Multiple bar charts with different baselines

10 views (last 30 days)
Hey all,
I intend to plot a recorded spectrum (the black line in the figure below) together with bar charts that are located at certain x-values. These bar charts should have different colors and be stacked above each other (be independent) as shown in the figure. However, the (simplified) code below does not result in such a plot. What could I try to change to make it work?
% line plot
x1=1:10;
y1=1:10;
%bar 1 data
xb1 = [2 5 7];
yb1 = [4 4 4];
%bar 2 data
xb2 = [1 2 9];
yb2 = [2 2 2];
figure
p1 = plot(x1,y1);
hold on
b1 = bar(xb1,yb1-2,0.2,'BaseValue',-2);
b2 = bar(xb2,yb2-6,0.2,'r','BaseValue',-6);
end
Thanks in advance!
bearli

Accepted Answer

Star Strider
Star Strider on 17 Sep 2015
You can plot the vertical lines using the plot function. The ‘trick’ is to duplicate the x and y values as matrix arguments:
% line plot
x1=1:10;
y1=1:10;
%bar 1 data
xb1 = [2 5 7];
yb1 = [4 4 4];
%bar 2 data
xb2 = [1 2 9];
yb2 = [2 2 2];
figure
p1 = plot(x1,y1);
hold on
b1 = plot([xb1; xb1], [yb1-2; yb1],'-b');
b2 = plot([xb2; xb2], [yb2-6; yb2],'-r');
axis([0 10 ylim])
You will likely need to experiment to get the result you want, but this should give you a start.
  2 Comments
bearli2
bearli2 on 17 Sep 2015
Edited: bearli2 on 17 Sep 2015
thanks for the idea!
I had to adapt it a bit like follows:
% line plot
x1=1:10;
y1=1:10;
%bar 1 data
xb1 = [2 5 7];
yb1 = [2 2 2];
%bar 2 data
xb2 = [1 2 9];
yb2 = [2 2 2];
figure
p1 = plot(x1,y1);
hold on
dist1 = -10;
dist2 = -20;
b1 = plot([xb1; xb1], [yb1+dist1; ones(1,size(yb1,2)).*dist1],'-b');
b2 = plot([xb2; xb2], [yb2+dist2; ones(1,size(yb2,2)).*dist2],'-r');
axis([0 10 ylim])
end
Star Strider
Star Strider on 17 Sep 2015
My pleasure!
I’m glad you got it working as you want it.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!