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:
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:
So how can I produce a one-bar stacked bar chart?
Select the data that you want to display in the form of a chart. In the Insert tab, click Column Charts (in Charts section) and select “2-D stacked bar.” A chart appears, as shown in the following image. The stacked bar chart compares the sales revenue generated in different months with respect to time.
Specify Axes for Bar GraphCall the tiledlayout function to create a 2-by-1 tiled chart layout. Call the nexttile function to create the axes objects ax1 and ax2 . Display a bar graph in the top axes. In the bottom axes, display a stacked bar graph of the same data.
(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)
:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With