Legend with multiple colors for a single bar plot

4 ビュー (過去 30 日間)
Kenneth
Kenneth 2014 年 5 月 8 日
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);

採用された回答

Michael Haderlein
Michael Haderlein 2014 年 5 月 8 日
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 件のコメント
Kenneth
Kenneth 2014 年 5 月 9 日
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 2021 年 5 月 15 日
Dear Michael,
your solution it's still useful in 2021!
Thanks for your help.
Best!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLegend についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by