2

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.

David M.
  • 186
  • 2
  • 8
  • Possible duplicate of [Combine the 'grouped' and 'stacked' in a BAR plot?](https://stackoverflow.com/questions/21304962/combine-the-grouped-and-stacked-in-a-bar-plot) – Anthony Nov 06 '18 at 22:05
  • @Anthony: It's not grouping. It's stacking with each bar having a different color, so not a duplicate. – gnovice Nov 06 '18 at 22:10
  • @gnovice, you are correct. Sorry I falsely judged it. – Anthony Nov 06 '18 at 22:17

1 Answers1

6

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
gnovice
  • 125,304
  • 15
  • 256
  • 359