필터 지우기
필터 지우기

Reproduce a legend in multiple figures

조회 수: 7 (최근 30일)
Chad Greene
Chad Greene 2012년 3월 19일
답변: Nahashon O 2022년 4월 4일
I have several figures. In figure 1 I specify a legend and format it nicely. It goes something like this:
figure(1)
plot(x,y1,x,y2,x,y3)
hleg = legend('string 1','string 2','string 3','orientation', 'horizontal', 'location','north'))
I would like to place the exact same legend in figure 2, regardless of what I'm plotting in figure 2. The following does not work:
figure(2)
plot(x,y4,x,y5)
legend(hleg)
How can I get my legend from figure 1 into figure 2?

답변 (2개)

Rick Rosson
Rick Rosson 2012년 3월 20일
You can create a function that takes an axes handle as an input argument, creates the legend as desired, and then returns the handle to the legend.
The function signature would be:
function Lgd = createLegend(ax)
Lgd = legend(ax, ... );
end
HTH.

Nahashon O
Nahashon O 2022년 4월 4일
You can create a cell array with the legend names, then pass the array whenever you call legend in your plots. i.e:
legend_names = { 'legend1', 'legend2'};
figure;
subplot(2,2,1)
plot(x1, y1);
hold on
plot(x1_1, y1_1)
legend(legend_names)
subplot(2,2,2)
plot(x2, y2);
hold on
plot(x2_1, y2_1)
legend(legend_names)
subplot(2,2,3)
plot(x3, y3);
hold on
plot(x3_1, y3_1)
legend(legend_names)
subplot(2,2,4)
plot(x4, y4);
hold on
plot(x4_1, y4_1)
legend(legend_names)

카테고리

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