MATLAB Answers

Perserving a legend when running a script manually multiple times

2 views (last 30 days)
Chay Weaver
Chay Weaver on 22 Mar 2021
Answered: Adam Danz on 23 Mar 2021
I am using Matlab 2019b and the app builder to run a function when a button in the application is clicked. The funcation outputs the data to make it accesible within the app builder 'code view'. That data is then passed into a different function contained with the application. This function plots the data and creates a legend.
I would like to be able to have the user run the app, see the figure, then change parameters in the app and run it again and see the new data apprear on the same figure. When the app is run for the second time the line shows on the plot in a different color as expected, however the legend overwrites the previous legend and doesn't perserve the entry from the first 'run'. How to I perserve the legend and keep adding data to the figure while perserving the legend?
Note: I have tried using hold on, hold all, ... doesn't seem to work.
After running app once:
After updating some inputs and running app again:

Answers (2)

Adam Danz
Adam Danz on 23 Mar 2021
It's better to use the DisplayName property of graphics objects to defiine the legend strings.
Here's a demo
Original creation of the figure
fig = figure();
ax = axes(fig);
plot(ax, 1:10, rand(1,10), 'DisplayName', 'Line 1')
legend(ax)
hold(ax,'on')
Add a line to the plot
Specify the same axis handle and define a new legend string as the DisplayName
plot(ax,1:10, rand(1,10),'DisplayName','Line 2')

Geoff Hayes
Geoff Hayes on 23 Mar 2021
Chay - how are you calling legend? Are you only passing a single label that you are hoping is applied to all plots? I think that might be the problem and that you need to pass a label for each curve that has been drawn (plotted) to the axes. Something similar to the following might work
close all;
x = -2*pi:0.01:2*pi;
y = sin(x);
plot(x,y);
legend(repmat('sine curve', length(get(gca,'Children')),1));
hold on;
plot(x,y+2);
legend(repmat('sine curve', length(get(gca,'Children')),1));
The same line of code is used to generate the legend whether there is one or two curves drawn to it. We rely on the number of children (the curves) to indicate how many times the string "sine curve" should be replicated. Note that this was tested on 2020a so may be slightly different on your version of MATLAB. Note that if I just use
legend(repmat('sine curve');
both times, then only one curve will appear in the legend.

Community Treasure Hunt

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

Start Hunting!