user3336190
user3336190

Reputation: 233

How to draw a group by boxplot in matlab

I have a three groups such as

Group 1={x1,x2}

   x1=[1,2,2,3,5,3]
   x2=[2,5,4,5,8,6]

Group 2={x3,x4}

   x3=[2,8,9,2,1,6]
   x4=[5,4,3,22,11,6]

Group 2={x5,x6}

   x5=[10,12,22,4]
   x6=[12,15,4,25]

I want to draw them into char by boxplot function by group. I found the way to resolve it. But it cannot draw. Could you help me please?

x1=[1,2,2,3,5,3];
x2=[2,5,4,5,8,6];
g1={x1,x2};
%group2
x3=[2,8,9,2,1,6];
x4=[5,4,3,22,11,6];
g2={x3,x4};
%group3
x5=[10,12,22,4];
x6=[12,15,4,25];
g3={x5,x6};


G=cat(1,g1,g2,g3); 
class={1,2,3}
positions = [1 1.25 2 2.25 3 3.25];
boxplot(G,class, 'positions', positions);

set(gca,'xtick',[mean(positions(1:2)) mean(positions(3:4)) mean(positions(5:6)) ])
set(gca,'xticklabel',{'Group1','Group2','Group3'})

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

enter image description here

Upvotes: 1

Views: 3387

Answers (1)

bdecaf
bdecaf

Reputation: 4732

Your problem is that the grouping variables were constructed in the wrong way. Use this sample:

x1=[1,2,2,3,5,3];
x2=[2,5,4,5,8,6];
g1=[x1,x2];
v1=[repmat('A',1,numel(x1)),repmat('B',1,numel(x2))];
%group2
x3=[2,8,9,2,1,6];
x4=[5,4,3,22,11,6];
g2=[x3,x4];
v2=[repmat('A',1,numel(x3)),repmat('B',1,numel(x4))];
%group3
x5=[10,12,22,4];
x6=[12,15,4,25];
g3=[x5,x6];
v3=[repmat('A',1,numel(x5)),repmat('B',1,numel(x6))];
%%

G=[g1,g2,g3]
vg1 = [repmat('1',1,numel(v1)),repmat('2',1,numel(v2)),repmat('3',1,numel(v3))];
vg2=[v1,v2,v3] ;
%%
clc
boxplot(G', {vg1';vg2'}, 'factorseparator',1 , 'factorgap',30,...
    'colorgroup',vg2','labelverbosity','majorminor');

Upvotes: 4

Related Questions