Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 694
Thomas Arildsen Avatar asked Feb 11 '20 17:02

Thomas Arildsen


People also ask

How do you plot a 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.

How do you plot a bar chart or graph in Matlab?

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.


Video Answer


1 Answers

(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

like image 197
Daniel Avatar answered Nov 03 '22 13:11

Daniel