Legend in Boxplot, colours don't match
10 次查看(过去 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.
0 个评论
回答(1 个)
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
2022-3-23
I tried this solution and it worked out perfectly for the same solution.
Thank you for your help!
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!