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

106 次查看(过去 30 天)
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!

回答(2 个)

Adam
Adam 2023-11-15
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 Adjacent Value)
Line (Lower Adjacent Value)
Line (Upper Adjacent Value)
Line (Upper Adjacent Value)
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.

Robert Groth
Robert Groth 2024-8-16
I just found your question along with the answer from Adam. I have made a function which will let you easily implement Adam's solution, which you can find here along with some example code.
Since your symbol is '.', it has no property for MarkerFaceColor, so instead you should plot it as 'o'.
The solution for your problem using BoxPlotFormat would be (including changing the outlier marker):
BoxPlotFormat(gca,'all','Median','Color','k','Whiskers','Color','k','WhiskerCaps','Color','k','Outliers','Marker','o','Outliers','MarkerEdgeColor','k')
BoxPlotFormat(gca,1,'Outliers','MarkerFaceColor',colors(2,1:3))
BoxPlotFormat(gca,2,'Outliers','MarkerFaceColor',colors(1,1:3))
I'm sure this will be fixed in the future, but this is a fine bandaid solution.

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by