MATLAB中的堆叠条形图

时间:2018-11-06 21:35:28

标签: matlab bar-chart stacked-chart

我正在尝试在MATLAB中创建一个条形图,其中条形位置位于一列中,条形高度位于另一列中,并且当两个或多个位置重叠时,条形就会堆叠起来。

为说明起见,这是在R中使用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

为进行比较,在MATLAB中,相同的数据如下:

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

但是我无法弄清楚bar函数是否有参数组合来创建相同类型的堆叠条形图。

1 个答案:

答案 0 :(得分:6)

这是完成此任务的一种方法(在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


关键是将传递给bar的数据格式化为矩阵,以使每一行包含一个堆栈的值,并且每一列将成为具有不同颜色的不同分组。基本上,barData最终基本上都是零,每列有一个非零值:

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
相关问题