David M.
David M.

Reputation: 186

Stacked bar chart in MATLAB

I'm trying to create a bar chart in MATLAB where bar positions are in one column, bar heights are in another, and the bars are stacked whenever two or more positions overlap.

To illustrate, here is the same chart created in R with ggplot:

library(ggplot2)

data <- data.frame(name=c('A', 'B', 'C', 'D', 'E', 'F'),
                   pos=c(0.1, 0.2, 0.2, 0.7, 0.7, 0.9),
                   height=c(2, 4, 1, 3, 2, 1))

ggplot(data, aes(x=pos, y=height, fill=name)) +
  geom_bar(stat='identity', width=0.05)

stacked bar chart created in R

For comparison, in MATLAB, the same data looks like:

data = [ 0.1, 0.2, 0.2, 0.7, 0.7, 0.9; ... 
    2, 4, 1, 3, 2, 1]';

But I can't figure out whether there's a combination of parameters to the bar function to create the same sort of stacked bar chart.

Upvotes: 2

Views: 668

Answers (1)

gnovice
gnovice

Reputation: 125854

Here's one way to accomplish this (it's a bit trickier in MATLAB):

[binCenters, ~, binIndex] = unique(data(:,1));
nBins = numel(binCenters);
nBars = numel(binIndex);
barData = zeros(nBins, nBars);
barData(binIndex+nBins.*(0:(nBars-1)).') = data(:, 2);
bar(binCenters, barData, 'stacked');
legend('A', 'B', 'C', 'D', 'E', 'F');

enter image description here


The key is to format the data passed to bar into a matrix such that each row contains values for one stack, and each column will be a different grouping with different colors. Basically, barData ends up being mostly zeroes with one non-zero value per column:

barData =

     2     0     0     0     0     0
     0     4     1     0     0     0
     0     0     0     3     2     0
     0     0     0     0     0     1

Upvotes: 6

Related Questions