how to fill boxes in Boxplot with different colors

757 views (last 30 days)
Hello, I would like to plot boxplot with each of the boxes with separate colors, I came across these set of code from this link: https://groups.google.com/forum/#!topic/comp.soft-sys.matlab/JFi976iIuZE However, with this link, all boxes are right now shaded with yellow. In contrast, I am interested in each of the boxes gets filled with different colors, for example, blue, red and gray. Any way, how to achieve this? Thanks,
  1 Comment
BN
BN on 5 Apr 2020
Edited: BN on 5 Apr 2020
Dear Poulomi
I have a same question, 2 years after you ... did you find any answer by the way?
regards

Sign in to comment.

Answers (2)

Ameer Hamza
Ameer Hamza on 5 Apr 2020
Edited: Ameer Hamza on 12 May 2020
Following the method in link posted by Poulomi, you can get different colors like this
data = rand(100, 4);
x = 1:4;
colors = rand(4, 3);
boxplot(data, x);
h = findobj(gca,'Tag','Box');
for j=1:length(h)
patch(get(h(j),'XData'),get(h(j),'YData'),colors(j,:),'FaceAlpha',.5);
end
If you are using R2020a, then use the following code, which is robust as compared to the above version
data = rand(100, 4);
x = 1:4;
colors = rand(4, 3);
figure();
ax = axes();
hold(ax);
for i=1:4
boxchart(x(i)*ones(size(data(:,i))), data(:,i), 'BoxFaceColor', colors(i,:))
end
  3 Comments
Alberto Acri
Alberto Acri on 26 Apr 2022
How can I modify your code:
data = rand(100, 4);
x = 1:4;
colors = rand(4, 3);
boxplot(data, x);
h = findobj(gca,'Tag','Box');
for j=1:length(h)
patch(get(h(j),'XData'),get(h(j),'YData'),colors(j,:),'FaceAlpha',.5);
end
To manually set the color of each boxplot?
Thanks!!

Sign in to comment.


Mehri Mehrnia
Mehri Mehrnia on 7 Nov 2021
I want facecolor with command "boxplot" not "boxchart". Can anyone help?
The reason that I use boxplot, it's more handy for "legend"

Categories

Find more on Line 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!

Translated by