legend in 2d line plot

조회 수: 3 (최근 30일)
Richard
Richard 2012년 3월 8일
I'm plotting data in a for loop where I'm looping through two datasets so using plot...; hold on;plot...
I only want the legend for the first plot, but there doesn't seem to be a way of doing this. Any advice?
Failing this, is there a way of adding a graph onto a currently existing graph. So, that I could just plot the first with a legend and then plot the second on top of this without a legend?
The code I've written is shown below:
for i = 1:length(LakeName);
for ii = 1:length(CorrVariables)
fh{ii} = figure(ii);
plot(HiResDay,HiRes.(LakeName{i}).(CorrVariables{ii}),'linewidth',2,'color',cmap(i,:));hold on;
plot(LowResDay,LowRes.(LakeName{i}).(CorrVariables{ii}),'--k','linewidth',3);
hTitle = title ([CorrVariables{ii} ' 2011']);
hXLabel = xlabel('Time (Day of year)' );
hLegend = legend(LakeName{:});
end
end
This doesn't work as I expected; the legend shows the line for the first plot and then the second, then back to the first, so in the end I have the first legend entry in the designated color, then the second legend entry shown according to '--k'.

채택된 답변

the cyclist
the cyclist 2012년 3월 8일
Here is a simple example of using the handles of only the first plots when making the legend.
h1 = zeros(5,1);
h2 = zeros(5,1);
lineColor = rand(10,3);
figure
hold on
for i =1:5;
h1(i) = plot(rand(4,1),rand(4,1),'Color',lineColor(i,:)); % Plot some random data in a random color
h2(i) = plot(rand(4,1),2+rand(4,1),'Color',lineColor(5+i,:));
end
legendText = {'1','2','3','4','5'};
legend(h1,legendText); % Make legend using handles to only first plots
  댓글 수: 3
the cyclist
the cyclist 2012년 3월 8일
I was hoping you would see how this would generalize. The essence is that you need to create a vector of the handles to the ONLY the elements you want in the legend. Then use that vector of handles when you call the legend command.
That is what I did in my example. I built my vector of handles from only the first plot, and used that vector in the legend command.
Richard
Richard 2012년 3월 9일
finally got it, I needed to create a cell array for the handles of each figure. cheers.

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

추가 답변 (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