用多个y轴绘制条形图

沙朗亚

我有一些要用条形图表示的数据:

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)

但是,我想对每条线的前三个条使用一个y轴,对第四条使用不同的y轴AAA

我无法plotyy按照此处的建议使用因为我有太多条目。

您知道其他选择吗?

警告:当您使用不同数量的条形时,此解决方案无法轻松推广...最后介绍了另一种推广效果更好的方法

通过阅读文档,我看不出为什么plotyy不起作用(除了yyaxis在2016a中被弃用)。

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}));

在此处输入图片说明

但是我会问,仅仅使用它是否会更清楚 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

在此处输入图片说明


做到这一点的另一种方法是,不要乱搞offsetwidth变量,而只需y用一堆0s填充

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'));

在此处输入图片说明

您可以使用与上述相同的方法为图表着色。无论条形数量如何,这都应该概括。不幸的是,您无法控制组之间的间距大小。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章