Search code examples
matlabplotscalestackedhorizontal-scaling

How to scale each different sized bars to fill the plot in Stacked Barh?


I would like to make a visually good plot with horizontal stacked bar. My goal is to fill the area horizontally with each bars. If each sum of rows in the matrix would be equal, the result is fine, i would like exactly that one with different sum-value rows.

I can set the max value of a dataset to xlim.

But how can I stretch or scale the different sum-value-stackedbars?

Bar values are currently in the a bars, so the focus is on the visual appearence.

I would appreciate any help you could provide.

Here is an example dataset for the problem;

t = [2 19 10 0;2 17 13 0;2 14 17 0;0 14 18 2;1 11 22 1;0 15 19 2;1 12 23 1;1 16 20 1;1 20 16 1];
barh(t,'stacked');

for i = 1 : 9
    num(i) = sum(t(i,:));
end
xlim = max(num);

set(gca,'XLim',[0 xlim]);

Solution

  • I am not sure if I understand right but you said My goal is to fill the area horizontally with each bars. So check the code below, it may be what you mean:

    t     = [2 19 10 0;2 17 13 0;2 14 17 0;0 14 18 2;1 11 22 1;0 15 19 2;1 12 23 1;1 16 20 1;1 20 16 1];
    num   = sum(t, 2);
    xlim  = max(num);
    scale = xlim ./ num;
    t_new = t .* ( scale * ones(1, 4) );
    barh(t_new, 'stacked');
    set(gca,'XLim',[0 xlim]);
    

    This is the output: enter image description here