Legend in Boxplot, colours don't match

27 visualizaciones (últimos 30 días)
Emma Southall
Emma Southall el 18 de Ag. de 2017
Comentada: Patrick Malgaroli el 23 de Mzo. de 2022
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.

Respuestas (1)

Vikaasa Kumar
Vikaasa Kumar el 21 de Ag. de 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 comentario
Patrick Malgaroli
Patrick Malgaroli el 23 de Mzo. de 2022
I tried this solution and it worked out perfectly for the same solution.
Thank you for your help!

Iniciar sesión para comentar.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by