The most efficient way to draw grouped boxlot matlab

I have 3 vectors: Y=rand(1000,1) , X=Y-rand(1000,1) and ACTid=randi(6,1000,1) . I would like to create boxes from group Y and X corresponding to their group value 1: 6 (from ACTid).

It is rather ad-hoc and looks nasty

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

Now I have the data in the cell, but I can not figure out how to group them into a box. Any thoughts?

I found an aboxplot function that looks like this, but I do not want this, I would like the built-in boxplot because I convert it to matlab2tikz, and this one does not do it well.

enter image description here

EDIT

Thanks to Oleg: now we have a grouped box ... but the labels are all confused.

 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

How to add a legend?

+6
source share
2 answers

A two-line approach (although if you want to keep two-line xlables and center the ones on the first line, this will be a hacker):

 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) 

Result:

enter image description here

EDIT

In the center of the mark ...

 % 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)) 

Exporting in .png format will cause problems ...

+8
source

I had the same problem with grouping data in a field. Another limitation of mine was that different groups have different amounts of data. Based on the tutorial I found, this seems like a good solution that I would like to share with you:

 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 is a link to the tutorial.

+6
source

All Articles