最有效的绘制分组boxplot matlab的方法

时间:2013-04-12 12:30:22

标签: matlab

我有3个向量:Y=rand(1000,1)X=Y-rand(1000,1)ACTid=randi(6,1000,1)。 我想用Y和X组创建对应于它们的组值1:6(来自ACTid)的箱形图。

这是相当特别的,看起来很讨厌

for ii=
dummyY(ii)={Y(ACTid==ii)};
dummyX(ii)={X(ACTid==ii)}
end

现在我将数据放在一个单元格中,但无法解决如何在箱线图中对其进行分组的问题。有什么想法吗?

我发现aboxplot function看起来像这样,但我不想这样,我想要内置的boxplot函数,因为我将它转换为matlab2tikz而且这个没有'做得好。

enter image description here

修改

感谢Oleg:我们现在有一个分组的箱形图......但标签都是偏斜的。

xylabel = repmat({'Bleh','Blah'},1000,1); % need a legend instead, but doesn't appear possible
boxplot([Y(:,end); cfu], {repmat(ACTid,2,1), xylabel(:)} ,'factorgap',10,'color','rk')
set(gca,'xtick',1.5:3.2:50)
set(gca,'xticklabel',{'Direct care','Housekeeping','Mealtimes','Medication','Miscellaneous','Personal care'})
>> ylabel('Raw CFU counts (Y)')

enter image description here

如何添加图例?

2 个答案:

答案 0 :(得分:9)

双线方法(虽然如果你想保留两行xlables并将它们放在第一行中,那就是hackish):

Y     = rand(1000,1);
X     = Y-rand(1000,1);
ACTid = randi(6,1000,1);

xylabel = repmat('xy',1000,1);
boxplot([X; Y], {repmat(ACTid,2,1), xylabel(:)} ,'factorgap',10)

结果:

enter image description here

修改

以标签为中心......

% Retrieve handles to text labels
h = allchild(findall(gca,'type','hggroup'));

% Delete x, y labels
throw = findobj(h,'string','x','-or','string','y');
h     = setdiff(h,throw);
delete(throw);

% Center labels
mylbl  = {'this','is','a','pain','in...','guess!'};
hlbl   = findall(h,'type','text');
pos    = cell2mat(get(hlbl,'pos'));

% New centered position for first intra-group label
newPos = num2cell([mean(reshape(pos(:,1),2,[]))' pos(1:2:end,2:end)],2);
set(hlbl(1:2:end),{'pos'},newPos,{'string'},mylbl')

% delete second intra-group label
delete(hlbl(2:2:end))

导出为.png会导致问题......

答案 1 :(得分:9)

我在框图中对数据进行分组时遇到了同样的问题。我的另一个限制是不同的群体具有不同数量的数据点。根据我发现的教程,这似乎是一个很好的解决方案,我想与您分享:

x = [1,2,3,4,5,1,2,3,4,6];
group = [1,1,2,2,2,3,3,3,4,4];
positions = [1 1.25 2 2.25];
boxplot(x,group, 'positions', positions);

set(gca,'xtick',[mean(positions(1:2)) mean(positions(3:4)) ])
set(gca,'xticklabel',{'Direct care','Housekeeping'})

color = ['c', 'y', 'c', 'y'];
h = findobj(gca,'Tag','Box');
for j=1:length(h)
   patch(get(h(j),'XData'),get(h(j),'YData'),color(j),'FaceAlpha',.5);
end

c = get(gca, 'Children');

hleg1 = legend(c(1:2), 'Feature1', 'Feature2' );

colored grouped boxplot with varying group sizes

Here是教程的链接。