Search code examples
matlabbar-chartmatlab-figure

How can I plot a one-bar stacked bar chart in MATLAB?


If I do a

bar([1 2 3 4 5;2 3 4 5 1], 'stacked')

I get two bars of stacked values corresponding to the two rows of my data - as I expected: example of two-bar stacked bar chart

I would like to be able to similarly plot a stacked bar chart with only one bar, but if I try like this

bar([1 2 3 4 5], 'stacked')

I simply get five individual bars instead - no stacking: enter image description here

So how can I produce a one-bar stacked bar chart?


Solution

  • (This solution requires MATLAB 2019b)

    Quoting the documentation:

    bar(y) creates a bar graph with one bar for each element in y. If y is an m-by-n matrix, then bar creates m groups of n bars.

    bar(x,y) draws the bars at the locations specified by x.

    Using the first syntax, each element of a vector will become it's own bar. Using the second syntax, x defines how to understand a vector. In your case, you want a single stacked group:

    bar(1,[1 2 3 4 5], 'stacked')
    

    For comparison, with Y=rand(1,5): example