How to add space between group of box and whisker bars using boxchart?
47 次查看(过去 30 天)
显示 更早的评论
I have data from 4 subjects. I want to add gaps between the red, blue and green bars of each subject using boxchart. Any recommendations would be great!
tbl = MasterData
tbl.SubjectID = categorical(tbl.SubjectID)
Display_Type = {"R","L"};
tbl.TargetDisplay = categorical(tbl.TargetDisplay);
idx = (tbl.TargetDisplay == "L")
tbl_Left_Display = tbl(idx,:)
figure(2);
title('Box and Whisker Plots for Display "L"');
boxchart(tbl_Left_Display.SubjectID,tbl_Left_Display.HorizontalFinalOffset,'GroupByColor',tbl_Left_Display.Color,'Notch','on','BoxWidth',1)
colororder([0 0 1;0 1 0; 1 0 0])
ylim([-8,8])
ylabel('Horizontal Final Offsets')
legend
Example data:
Color HorizontalFinalOffset TargetDisplay SubjectID
_____ _____________________ _____________ _________
{'B'} -1.4175 {'L'} {'JD'}
{'R'} -2.0716 {'L'} {'JD'}
{'G'} 0 {'L'} {'JD'}
{'R'} 2.4858 {'R'} {'JD'}
{'B'} -0.19851 {'R'} {'JD'}
{'G'} 0 {'R'} {'JD'}
{'R'} -2.4937 {'L'} {'JD'}
{'B'} -0.97587 {'L'} {'JD'}
{'G'} 0 {'L'} {'JD'}
{'R'} -0.66174 {'L'} {'JD'}
0 个评论
采纳的回答
Voss
2023-8-21
编辑:Voss
2023-8-21
First, I make table variables like yours:
d = {'R';'L'};
s = {'JD';'MM';'SH';'YL'};
c = {'B';'G';'R'};
Npts = 1000;
Color = c(randi(numel(c),Npts,1));
HorizontalFinalOffset = 2*randn(Npts,1);
TargetDisplay = d(randi(numel(d),Npts,1));
SubjectID = s(randi(numel(s),Npts,1));
tbl = table(Color,HorizontalFinalOffset,TargetDisplay,SubjectID);
tbl.SubjectID = categorical(tbl.SubjectID);
tbl.TargetDisplay = categorical(tbl.TargetDisplay);
idx = (tbl.TargetDisplay == "L");
tbl_Left_Display = tbl(idx,:)
The boxchart, as you have it already:
figure()
b = boxchart(tbl_Left_Display.SubjectID,tbl_Left_Display.HorizontalFinalOffset,'GroupByColor',tbl_Left_Display.Color,'Notch','on','BoxWidth',1);
colororder([0 0 1; 0 1 0; 1 0 0])
ylim([-8,8])
ylabel('Horizontal Final Offsets')
legend
Now, modifying the gaps between the boxcharts:
Option 1: decreasing 'BoxWidth':
figure()
b = boxchart(tbl_Left_Display.SubjectID,tbl_Left_Display.HorizontalFinalOffset,'GroupByColor',tbl_Left_Display.Color,'Notch','on','BoxWidth',0.5);
colororder([0 0 1; 0 1 0; 1 0 0])
ylim([-8,8])
ylabel('Horizontal Final Offsets')
legend
Option 2: manually setting the XData (adjust as desired):
[s,~,xx] = unique(tbl_Left_Display.SubjectID);
ns = numel(s);
c = {'B';'G';'R'};
nc = numel(c);
figure()
hold on
if nc > 1
offset = 1/max(3,7-nc);
offset = linspace(-offset,offset,nc);
else
offset = 0;
end
width = 1/(2*nc);
for ii = 1:nc
idx = strcmp(tbl_Left_Display.Color,c{ii});
y = tbl_Left_Display.HorizontalFinalOffset(idx);
x = xx(idx)+offset(ii);
boxchart(x,y,'Notch','on','BoxWidth',width);
end
colororder([0 0 1; 0 1 0; 1 0 0])
xlim([0.5 ns+0.5])
xticks(1:ns)
xticklabels(s)
ylim([-8,8])
ylabel('Horizontal Final Offsets')
legend(c)
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!