Changing colors of outlier markers, median and whiskers in a box and whisker plot

68 views (last 30 days)
Federico Naos on 15 Nov 2023
Hello,
So, currently I have the following script to generate a box and whisker plot:
x1 = randn(128, 1);
x2 = randn(100, 1);
X = [x1; x2];
colors = [0 0.4470 0.7410; 0.8500 0.3250 0.0980];
grp = [ones(size(x1)); 2.*ones(size(x2))];
h = boxplot(X, grp, ...
'Colors',colors, ...
'Symbol','.')
for j=1:size(h,2)
patch(get(h(5,j),'XData'),get(h(5,j),'YData'),get(h(5,j),'Color'),'FaceAlpha',.7);
end
The result I get is this one:
What I would like to do is to make the whisker line, the median line and the outline markers all black. The end result would be something like this:
Thanks!

I'm surprised boxplot has no option to return any graphics handles like most plotting functions do, but you can do the ugly approach of searching for them after plottiing:
>> upperWhiskers = findobj( gca, 'tag', 'Upper Whisker' )
upperWhiskers =
2×1 Line array:
Line (Upper Whisker)
Line (Upper Whisker)
Then you can manipulate each line object in any way you wish, including the colour.
The component lines are all part of a group and each has a tag that you can search for to make it fairly robust. These are:
>> ch(3).Children
ans =
14×1 Line array:
Line (Outliers)
Line (Outliers)
Line (Median)
Line (Median)
Line (Box)
Line (Box)
Line (Lower Whisker)
Line (Lower Whisker)
Line (Upper Whisker)
Line (Upper Whisker)
Ignore the ch(3) there, that was just me searching the children of my axes to find the relevant objects. I just posted this to give you all the relevant tags. There will be one of each for each plot, so if you had 7 box plots you'd end up with 7 Upper Whisker lines, etc.

Categories

Find more on Box Plots in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!