How to plot two bar plot in the same figure?

108 views (last 30 days)
Dear all,
I am wondering how to make a figure in matlab composed by two bar plots, the first contentive of several vaklues I want to make this stacked, this is a easy going job, but the problem arise when I attemp to set another bar plot next to the first one (the stacked), I need to make this in order to make a comparison.
I attempted with this but it does not work Y1=bar([U1, 'stacked'], [Mean], barWidth);
In the end, I just want to set a non-stacked bar plot next to the corresponding stacked one, like the black one I have drawn in the figure above. Just to remark it should not be overlapped but I did not have enough spafe in between the stacked ones.
I kindly ask for your insights in this matter.
Best regards

Accepted Answer

Scott MacKenzie
Scott MacKenzie on 28 Jun 2021
Edited: Scott MacKenzie on 29 Jun 2021
There are a few ways to do this. The best option in any situation depends on how your data are organized (or can be organized) and the amount of fiddling necessary to get the desired bar colours, tick labels, etc.
This first solution plots two sets of data, one stacked and the other with single bars. The bar widths and positions are adjusted as per your needs. There is a tick label for each group of unstacked+stacked bars.
n = 5;
x1 = rand(2,n)
x2 = 2 * rand(1,n);
b1 = bar(x1','stacked');
hold on;
b1(1).BarWidth = .4;
b1(1).XData = (1:n) + .25; % move stacked bars right
b1(2).XData = (1:n) + .25;
b2 = bar(x2);
b2.BarWidth = 0.4;
b2.XData = (1:n) - .25; % move single bars left
The second solution expands the two sets of data to include 0s either in the odd positions for the stacked bars or in the even positions for the single bars. Each bar has an x-axis tick and tick label.
n = 10;
odd = ~rem(1:n,2);
even = rem(1:n,2)
x1 = rand(2,n) .* odd;
x2 = 2 * rand(1,n) .* even;
b1 = bar(x1','stacked');
hold on;
b2 = bar(x2);
The third solution uses a single set of data but nulls out the odd entries in one column. All the bars are stacked but half the values in one set are zero.
n = 10;
odd = logical(rem(1:n,2));
x = rand(2,n)';
x(odd,1) = 0; % make every second value 0 in 1st column
Tony Castillo
Tony Castillo on 29 Jun 2021
Yes it is a bit challenging, but I have addressed it using your first solution, thank you very much for your attitude dealing with this.

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!