如何在MATLAB中使用分组和堆叠样式创建一个barseries图? [英] How can I create a barseries plot using both grouped and stacked styles in MATLAB?
问题描述
MATLAB 为您绘制一个组合分组/堆积条形图。但是,您可以自行完成,无论您想要分隔条组,都可以向您的 Y
数据添加零行,然后修改x轴刻度标记和勾选标签。例如:
>> Y = [1 2 3; ...%#示例数据
2 3 4; ...
3 4 5; ...
4 5 6; ...
5 6 7; ...
6 7 8; ...
7 8 9; ...
8 9 10; ...
9 10 11];
>> newY = reshape([reshape(Y,3,[]); zeros(1,numel(Y)/ 3)],[],3)%#为空格添加零
%#$ b $ newY =
1 2 3
2 3 4
3 4 5
0 0 0%#< - 注意零行
4 5 6
5 6 7
6 7 8
0 0 0
7 8 9
8 9 10
9 10 11
0 0 0
>>巴(newY,叠加); %#创建堆积直方图
>> (gca,'XLim',[0 12],'XTick',2:4:10,'XTickLabel',1:3); %#修改坐标轴
以下是最终结果:
The MATLAB bar documentation states the following:
bar(...,'style') specifies the style of the bars. 'style' is 'grouped' or 'stacked'. Default mode of display is 'grouped'.
However, I would like to achieve both at the same time. Let me elaborate by giving an example:
Y = [1.0 0.5 0.7
2.0 1.5 2.0
5.0 4.0 5.0
4.0 4.0 4.5
3.0 2.0 2.0];
bar(Y,'group');
This code produces the following grouped barseries plot, with 5 different sets of 3 bars grouped together:
bar([repmat(0.5,5,1) Y(:,1)-0.5],'stack');
And this code produces the following stacked barseries plot, using just the first column of the above defined matrix Y
:
I would like to merge these two, to get a barseries plot which is grouped and stacked at the same time. So the desired result would be like the first picture and each of the three bars in a set would be stacked like the second picture.
There's no way I know of to get BAR to plot a combination grouped/stacked bar chart for you. However, you can do it yourself by adding rows of zeroes to your Y
data wherever you want groups of bars to be separated, then modifying the x-axis tick marks and tick labels accordingly. Here's an example:
>> Y = [1 2 3; ... %# Sample data
2 3 4; ...
3 4 5; ...
4 5 6; ...
5 6 7; ...
6 7 8; ...
7 8 9; ...
8 9 10; ...
9 10 11];
>> newY = reshape([reshape(Y,3,[]); zeros(1,numel(Y)/3)],[],3) %# Add zeroes
%# for spacing
newY =
1 2 3
2 3 4
3 4 5
0 0 0 %# <--- Note zero rows
4 5 6
5 6 7
6 7 8
0 0 0
7 8 9
8 9 10
9 10 11
0 0 0
>> bar(newY,'stacked'); %# Create a stacked histogram
>> set(gca,'XLim',[0 12],'XTick',2:4:10,'XTickLabel',1:3); %# Modify axes
And here's the resulting figure:
这篇关于如何在MATLAB中使用分组和堆叠样式创建一个barseries图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!