How do I edit the legend when I have *many* entries (but only 2 types of data)

조회 수: 82 (최근 30일)
Hello Community,
I have a presentation problem regarding a plot legend that I hope you can help with. This situation is that I plot a bar chart and need to identify a single bar with a different colour when the data hits certain conditions, coded as:
% raise figure
figure(1)
hold on
% set color bar
cm = [0.90 0.90 0.90; 0 0 0];
% run for loop to colour data individually & when data conditions are met
for i = 1:length(pltvar1srt)
h=bar(i,pltvar1srt(i));
if pltvar1srt(i) == 1.71 && 4
set(h,'FaceColor',cm(1,:));
else
set(h,'FaceColor',cm(2,:));
end
end
hold off
and this produces the plot I need:
The problem is when I add the legend, due to the way I have coloured the bar, I get many data entries:
Using the legend help, I have tried to write the legend using a variety of calls - all of which haven't worked unfortunately:
legend ([data1 data10]);
legend ([data data10]);
legend ([pltvar1srt.9 pltvar1srt.10]);
legend ([pltvar1srt(9) pltvar1srt(10)]);
legend ([cm(1,:) cm(2,:)], 'Data 1', 'Data 2');
% etc. etc.
but still no luck. I have also looked at this useful function - but again, couldn't get it to work in the way I needed.
I simply want the legend to have the two entries ie 'Black Data' and 'Grey Data' and be coloured appropriately.
Can anyone offer any help please?
Many thanks,
10B.
  댓글 수: 1
10B
10B 2016년 7월 19일
Reading through various examples, I starting to think that 'hggroup' may be part of the solution, similar to the example here, the drawback is that I am not creating the plot in the same way.
I'm still working on this - but would be grateful of some help if possible!

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

채택된 답변

Thorsten
Thorsten 2016년 7월 19일
if pltvar1srt(i) == 1.71 && 4
set(h,'FaceColor',cm(1,:));
hlegend(1) = h;
else
set(h,'FaceColor',cm(2,:));
hlegend(2) = h;
end
and then
legend(hlegend, {'Data 1' 'Data 2'})
  댓글 수: 1
10B
10B 2016년 7월 21일
편집: 10B 2016년 7월 21일
Ah! Of course - Many thanks Thorsten.
I had experimented with:
h=set(h,'FaceColor',cm(1,:)); etc.
at one point which obviously didn't work, but I was sort of along the right track, so thanks for helping me out.
You never know, in just 5 or 6 more years of this pain, I may just learn to master the basics...

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

추가 답변 (1개)

Sharad Singhania
Sharad Singhania 2019년 7월 14일
You can also do it from plot editor.
Go to plot editor > Property editor -Legend > more properties... > string > click on array icon> modify as per your requirement.

카테고리

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