Color each boxplot differently

I found an example that allows you to color with random colors. However, I want to color the inside of each boxplot with a certain color.
a = magic(3);
boxplot(a)
i = 3; % number of boxplots
x = 1:i;
colors = rand(i, 3);
figure
boxplot(a, x,'Whisker', inf);
h = findobj(gca,'Tag','Box');
for j=1:length(h)
patch(get(h(j),'XData'),get(h(j),'YData'),colors(j,:),'FaceAlpha',.5);
end
I would also like to make the lines thicker. How can I do this?

回答 (2 件)

Jon
Jon 2022 年 4 月 26 日

0 投票

I think this should get you closer to what you want. You can select other colors using their rgb color codes, I just used red,green and blue in the example
a = magic(3);
boxplot(a)
i = 3; % number of boxplots
x = 1:i;
colors = [1 0 0;0 1 0;0 0 1];
figure
boxplot(a, x,'BoxStyle','outline','Colors',colors);
h = findobj(gca,'Tag','Box');
for j=1:length(h)
patch(get(h(j),'XData'),get(h(j),'YData'),get(h(j),'Color'),'FaceAlpha',.5);
end

3 件のコメント

Jon
Jon 2022 年 4 月 26 日
You can also change the linewidth as follows
a = magic(3);
boxplot(a)
i = 3; % number of boxplots
x = 1:i;
colors = [1 0 0;0 1 0;0 0 1];
lineWidth = 2;
figure
boxplot(a, x,'BoxStyle','outline','Colors',colors)
h = findobj(gca,'Tag','Box');
for j=1:length(h)
set(h(j),'LineWidth',lineWidth)
patch(get(h(j),'XData'),get(h(j),'YData'),get(h(j),'Color'),'FaceAlpha',.5);
end
Alberto Acri
Alberto Acri 2022 年 4 月 26 日
I was interested in having an increase in the thickness of all the lines in the figure. See below:
Jon
Jon 2022 年 4 月 26 日
If you are running R2020A or higher you may want to investigate boxchart. It seems to offer the options you want more directly

サインインしてコメントする。

Baldvin
Baldvin 2025 年 11 月 13 日

0 投票

As has been pointed out, boxchart (documentation) was introduced in R2020a and offers flexibility with coloring of the face of boxes (and much more):
a=magic(3);
b=boxchart(a(:),'GroupByColor',repelem(1:3,3));
get(b,'BoxFaceColor')
ans = 3×1 cell array
{[0.0660 0.4430 0.7450]} {[ 0.8660 0.3290 0]} {[0.9290 0.6940 0.1250]}
This property enables you to do exactly what you want to do. For example, if you wanted to change the color of the first blue box, b(1).BoxFaceColor = 'm';
BoxChart Properties documentation, especially the "Color and Styling" section, shows many more properties that might be of interest.

製品

リリース

R2021b

質問済み:

2022 年 4 月 26 日

回答済み:

2025 年 11 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by