Add variable names to figure legends

41 views (last 30 days)
Ganesh
Ganesh on 22 Dec 2023
Commented: Paul on 22 Dec 2023
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.

Answers (2)

Paul
Paul on 22 Dec 2023
Hi Ganesh,
Add a second argument to the legend command
% what you have
figure
h = plot(rand(3));
legend(h)
% what you want
figure
h = plot(rand(3));
legend(h,{'first','second','third'})
See legend for all options on the labels argument.
  2 Comments
Ganesh
Ganesh on 22 Dec 2023
Hi Paul, thanks for the answer. My stored variable “beats_Local_var1_W1” value contains the incremental values (in this case includes 5000, 5500,….8000), and I would like to reflect the same in the legend. Also, these values may change dynamically for other cases (the number of lines may vary each time). So is there a way I could read the contents from each data (data1 (5000), data2(5500),…) and display them as a legend? Sorry, I should have been a bit clear on this.
Paul
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?

Sign in to comment.


Steven Lord
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

Products

Community Treasure Hunt

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

Start Hunting!