Legend in Boxplot, colours don't match

조회 수: 27 (최근 30일)
Emma Southall
Emma Southall 2017년 8월 18일
댓글: Patrick Malgaroli 2022년 3월 23일
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