Legend in Boxplot, colours don't match
9 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (1)
Vikaasa Kumar
il 21 Ago 2017
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 Commento
Patrick Malgaroli
il 23 Mar 2022
I tried this solution and it worked out perfectly for the same solution.
Thank you for your help!
Vedere anche
Categorie
Scopri di più su Legend in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!