Legend in Boxplot, colours don't match

27 次查看(过去 30 天)
Hi, My problem is when I make a legend for my boxplots, they all have the same colours. I've read other solutions online however since I have 54 boxplots I don't want to manually enter their colours. This is my code,
PR1 = boxplot(dataset, titles);
set(gca, 'xtick', []);
set(findobj(gca,'type','line'),'linew',2);
h = findobj(gca,'Tag','Box');
CM = hsv(54);
for j=1:length(h)
patch(get(h(j),'XData'),get(h(j),'YData'), CM(j,:),'FaceAlpha',.5);
end
legend(h, titles, 'location', 'Westoutside')
I've also attached an image of the graphic so you can see the problem.

回答(1 个)

Vikaasa Kumar
Vikaasa Kumar 2017-8-21
Hi Emma,
Here, "h" is being constructed as a Line array, with all the lines set to color [0 0 1], which is blue. Since you are making the legend passing "h" and "titles" as arguments, the legend results with a set of blue lines.
This can be resolved by setting the line color in "h" to the patch color within the for-loop, as shown in the following modified code snippet:
PR1 = boxplot(dataset, titles);
set(gca, 'xtick', []);
set(findobj(gca,'type','line'),'linew',2);
h = findobj(gca,'Tag','Box');
CM = hsv(54);
for j=1:length(h)
x = patch(get(h(j),'XData'),get(h(j),'YData'), CM(j,:),'FaceAlpha',.5);
% MODIFICATION TO SET THE LINE COLOR TO PATCH COLOR:
h(length(h)-j+1).Color = x.FaceColor; % reordered to match
end
legend(h, titles, 'location', 'Westoutside')
Please let me know if this fixed the issue.
Best,
Vikaasa
  1 个评论
Patrick Malgaroli
Patrick Malgaroli 2022-3-23
I tried this solution and it worked out perfectly for the same solution.
Thank you for your help!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by