Legend with multiple colors for a single bar plot
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Kenneth
am 8 Mai 2014
Kommentiert: Giuseppe Degan Di Dieco
am 15 Mai 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);
0 Kommentare
Akzeptierte Antwort
Michael Haderlein
am 8 Mai 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 Kommentare
Giuseppe Degan Di Dieco
am 15 Mai 2021
Dear Michael,
your solution it's still useful in 2021!
Thanks for your help.
Best!
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Legend finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!