MATLAB: Multiple bar charts with different baselines

barcombineMATLABxrd

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

Best Answer

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.