制作多个y轴的条形图

时间:2016-06-13 08:31:44

标签: matlab

我想用条形图表示一些数据:

AAA=[2/3 1.5/3 .5/3 3; 1.5/3  1.8/3 .5/3 2.8];
figure
bar([1 2], AAA, 'BarWidth', 1)

但是我想在AAA的每一行的前三个条形图中使用一个y轴,而在第四个条形图中使用不同的一个条形图。

我无法按照建议here使用plotyy因为我的条目太多了。

你知道一些替代方案吗?

1 个答案:

答案 0 :(得分:4)

警告: 当你有不同数量的柱子时,这个解决方案不容易推广......一种更好地推广的不同方法在端

从阅读docs开始,我不明白为什么plotyy无法工作(除了在2016a中被赞成为yyaxis)。

  

plotyy(X1,Y1,X2,Y2,' function1',' function2')使用function1(X1,Y1)绘制左轴和function2(X2)的数据,Y2)绘制右轴的数据。

y1 = [2/3 1.5/3 .5/3; 1.5/3  1.8/3 .5/3];
y2 = [3; 2.8];
x = [1,2];
figure

% based on http://stackoverflow.com/questions/18688381/matlab-bar-plot-grouped-but-in-different-y-scales
offset = (x(2)-x(1))/16; %needs to be generalised, so the 16 should be something like 2^(size(y1,2)+1) or 2^(size(y1,2)+size(y2,2))
width = (x(2)-x(1))/4; %The 4 here also needs to be generalized
colors = {'b','g'};
plotyy(x-offset*5,y1,x+offset*2,y2, @(x,y) bar(x,y,width*4,colors{1}), @(x,y) bar(x,y,width,colors{2}));

enter image description here

但我会质疑是否更清楚地使用subplot

如果您想更改单个栏的颜色(每个类别),您必须手动执行:

h = plotyy(x-offset*5,y1,x+offset*2,y2, @(x,y) bar(x,y,width*4,colors{1}), @(x,y) bar(x,y,width,colors{2}));
barGroup1 = h(1).Children;
map1 = [0, 0, 0.4;
        0, 0, 0.6;
        0, 0, 1];
for b = 1:numel(barGroup1)
    barGroup1(b).FaceColor = map1(b,:);
end

enter image description here

执行此操作的另一种方法是使用offsetwidth变量,而不是使用y来填充每个0

y1 = [2/3 1.5/3 .5/3,1; 1.5/3  1.8/3 .5/3,1;1,1,1,1];
y2 = [3,1; 2.8,1;1,1];
x = [1,2,4]; %x doesn't need to go up in increments of 1 (spacing will differ as you can see in the image), however it can only contain integers
nCol = max(size(y1,2),size(y2,2))*2;
Y1 = zeros(size(y1,1),nCol);
Y2 = zeros(size(y2,1),nCol);
% The idea is the make all the bars from group 1 sit before the group number (i.e. the numbers going from the halfway mark backwards) and all the bars from group 2 sit after the halfway mark (i.e. the numbers from the middle(+1) going forward)
Y1(:,nCol/2-size(y1,2)+1:nCol/2) = y1
Y2(:,nCol/2+1:nCol/2+1+size(y2,2)-1) = y2
h = plotyy(x,Y1,x,Y2, @(x,y) bar(x,y,1,'b'), @(x,y) bar(x,y,1,'g'));

enter image description here

您可以使用与上面相同的方式为此图表着色。无论条数多少都应该概括。遗憾的是,您无法控制群组之间差距的大小。