Bar plot with a single bar across multiple x-axis values

I need to plot a single horizontal bar across multiple x-axis values, e.g.,
y=[2 1 3];
bar(1:6,y(1),'c', 2:5,y(2),'m', 6:10,y(3),'y');
I would like to see a single horizontal bar along x-axis: a) from 1 to 6 at a y-axis height of 2, b) from 2 to 5 at a y-axis height of 1, and c) from 6 to 10 at a y-axis height of 3. Could you please help me plot so?
Moreover, is there a possibility to [visually] distinguish the overlay bars (using colors or the like)? Because .. in the example provided above, the bar along x-axis 2 to 5 with height 1 units cannot be seen.

 Accepted Answer

This works:
y=[2 1 3];
figure(1)
patch([1 6 6 1], [0 0 2 2],'b')
hold on
patch([2 5 5 2],[0 0 1 1],'r')
patch([6 10 10 6],[0 0 3 3], 'g')
hold off
axis([1 10 0 5])
Make changes to the colours to your liking.
The plot:

4 Comments

That works! Just an addition, I am not able to specify the color of the patch using a loop. Neither 'Color' nor 'FaceColor' works. The error is: not enough input arguments I will appreciate support on this. I am trying to do this -
n=[1 6;
2 5;
6 10];
v=[2 1 3];
ColorS1 = [0.33 0.60 0.80
0.75 0.75 0.00
0.00 0.00 1.00
0.76 0.57 0.17
0.75 0.75 0.75
0.54 0.63 0.22];
for i=1:4
patch( [n(i,1) n(i,2) n(i,2) n(i,1)], [0 0 v(i) v(i)],
'FaceColor', ColorS1(i,:));
hold on;
end
My pleasure!
There were two errors:
  1. There are three rows in ‘n’ and as many elements in ‘v’, so the loop index has to be changed so you don’t get an ‘Index exceeds matrix dimensions’ error at i=4;
  2. Apparently you don’t need the 'FaceColor' name, only the three-element colour vector. (This came as a surprise to me, so I learned something!)
The loop therefore changes to:
for i=1:3
patch( [n(i,1) n(i,2) n(i,2) n(i,1)], [0 0 v(i) v(i)], ColorS1(i,:));
hold on;
end
and it should work as you want it to. The resulting plot looks good to me.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!