Add variable names to figure legends
41 views (last 30 days)
Show older comments
Hi all, I would like to add variable names to matlab plot 'legends'. My varibale is stored as "beats_Local_var1_W1" which contains several variable values. Note: I am plotting this outside the loop and the above variable stores all the data and variable information.
My code and plot are as follow:
Pplot = plot(detrend(Mynorm(beats_Local_var1_W1)));
xlabel('Time [samples]');
ylabel('Amplitude [norm]');
title(LocVariable)
legend(Pplot)

I would like to add actual names as legends instead of "data1", "data2" etc. Any help or direction would be highly appreciated.
0 Comments
Answers (2)
Paul
on 22 Dec 2023
2 Comments
Paul
on 22 Dec 2023
I'm afraid I don't understand what you mean. Based on the code above, the variable
beats_Local_var1_W1
is just an 2D matrix of numbers. So I don't understand how it can contain "incremental values" that can then be used to determine what goes in the legend.
Can save an example of your variables in a .mat file, upload it using the paper clip icon in the Insert menu, and then explain what information is contained in those variables that should be used to determine the legend entries?
Steven Lord
on 22 Dec 2023
So do you have variables named beats_Local_var1_W1, beats_Local_var1_W2, beats_Local_var1_W3, etc.?
If so can you dynamically create variables with numbered names like x1, x2, x3, etc.? Yes.
Should you do this? The general consensus is no. That Answers post explains why this is generally discouraged and offers several alternative approaches.
If you have a list of labels you want to use you could use the approach of passing the names into the legend function as @Paul showed, or you could set the DisplayName property of the line you plot. As an example:
x = 0:360;
plot(x, sind(x), 'DisplayName', 'sine curve');
legend show
0 Comments
See Also
Categories
Find more on Legend in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

