Reproduce a legend in multiple figures

10 views (last 30 days)
Chad Greene
Chad Greene on 19 Mar 2012
Answered: Nahashon O on 4 Apr 2022
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?

Answers (2)

Rick Rosson
Rick Rosson on 20 Mar 2012
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 on 4 Apr 2022
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)

Tags

Products

Community Treasure Hunt

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

Start Hunting!