필터 지우기
필터 지우기

How to have 2 legend entries for 1 set of data using bar plot?

조회 수: 5 (최근 30일)
Norris
Norris 2015년 8월 25일
댓글: Star Strider 2015년 8월 25일
I have a bar plot with 1 set of data and I colorized the bars to highlight some differences after a threshold. Now I would like to have 2 entries in the legend but I cant figure out how to do that.
Matlab recognizes there is only 1 set of data and adds only 1 legend entry. Smart Matlab...
Is there a way to disable this to? Or another suggestions?
% test data
data = 1:10;
% bar plot
bar_h = bar(data);
% colorize bars
bar_child = get(bar_h,'Children');
% create custom color map
mycolor=[0 0 1;1 0 0]; %set colors
colormap(mycolor)
blue = 1*(data<8);
red = 2*(data>=8);
index = blue + red;
% apply colors
set(bar_child,'CData',index);
% legend
legend('blue','red')
edit: added a picture of what I mean

채택된 답변

Star Strider
Star Strider 2015년 8월 25일
편집: Star Strider 2015년 8월 25일
One possibility:
% test data
data = 1:10;
data1 = data(data<8);
data2 = data(data>=8);
% bar plot
bar_h1 = bar([1:7], data1,'b');
hold on
bar_h2 = bar([8:10], data2,'r');
hold off
set(gca, 'XTick',[1:10])
legend('blue','red', 'Location','NW')
I’m using R2015a, so can’t use your ‘bar_child’ and related data and calls. The set call for the 'XTick' values was necessary because without it the ticks for [8:10] don’t plot for some reason, even when specifically stating them in the bar call. Weird.
EDIT — Added 'Location' to legend call.
  댓글 수: 2
Norris
Norris 2015년 8월 25일
편집: Norris 2015년 8월 25일
Works like a charm!! Thanks so much. I did try to split the data into 2 sets of bars but didnt get it to work earlier.
Cheers.
Star Strider
Star Strider 2015년 8월 25일
My pleasure.
Plotting two sets of bars requires the hold function, to be certain the second set of bars does not overplot the first set. I too had problems getting it to work as I wanted it to, thus the set call. (There are also version differences between R2014a and earlier, and R2014b and later, so I did my best to provide a ‘universal’ approach.)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by