Legend with multiple colors for a single bar plot

2 visualizaciones (últimos 30 días)
Kenneth
Kenneth el 8 de Mayo de 2014
Comentada: Giuseppe Degan Di Dieco el 15 de Mayo de 2021
I have a single bar plot and i have managed to color the bars in 3 different colors. When I try to create a legend, it does only show one color. How can i add the two other colors to the legend when i only have one bar plot?
My code looks like this:
figure(2)
bar_h = bar(T_orderO);
title('Tid brugt på hvert spørgsmål')
xlabel('Spørgsmålsnummer')
ylabel('Tid (s)')
set(gca,'XLim',[0 numel(O)+1])
set(gca,'xticklabel',O)
set(gca,'XTick',1:1:numel(O))
set(gca,'YLim',[0 max(T_orderO)*1.1])
%set(gca,'YTick',0:max(T_orderO)+1)
hbar_child = get(bar_h, 'Children');
set(hbar_child,'CData',T_orderO);
set(hbar_child,'CDataMapping','direct');
index = 1:numel((R_orderO));
for i = 1:length(R_orderO)
if R_orderO(i) == -1
index(i) = 1;
elseif R_orderO(i) == 1
index(i) = 2;
else
index(i) = 3;
end
end
mycolor=[1 0 0; 0 1 0; 1 1 1];
colormap(mycolor);
set(hbar_child, 'CData',index);

Respuesta aceptada

Michael Haderlein
Michael Haderlein el 8 de Mayo de 2014
Hi Kenneth,
I don't know if that's what you'd like to have, but I have used "invisible" plots to generate "artificial" legend entries. Just plot only one data point and set it to NaN:
figure, hold all
plot(1,nan,'k-') %legend entry 1
plot(1,nan,'ko') %legend entry 2
legend('Experiment','Simulation')
%actual data plots
plot(1:4,rand(1,4),'b-')
plot(1:4,rand(1,4),'bo')
plot(1:4,rand(1,4)+1,'r-')
plot(1:4,rand(1,4)+1,'ro')
plot(1:4,rand(1,4)+2,'g-')
plot(1:4,rand(1,4)+2,'go')
plot(1:4,rand(1,4)+3,'c-')
plot(1:4,rand(1,4)+3,'co')
That should be possible with bar plots, too.
Michael
  2 comentarios
Kenneth
Kenneth el 9 de Mayo de 2014
Hi Michael,
That was exactly what I wanted, and it works fine with bar plots too. Thanks a lot.
Kenneth
Giuseppe Degan Di Dieco
Giuseppe Degan Di Dieco el 15 de Mayo de 2021
Dear Michael,
your solution it's still useful in 2021!
Thanks for your help.
Best!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Legend en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by