Clear Filters
Clear Filters

How to add a legend to a plot from fitlm function?

25 views (last 30 days)
Hello! I created many plots and used the fitlm regression line to get my r squared, p value and slope. I want to add a text box or a legend in my plot to show r squared, p value and slope values. Is there any way I can automatically do this? i used to manually save the picture and create a small box with desired information but its too time consuming.
I wanted to use the str function but my r squared, p value and slope are calculated in the command window.
Thank you!!

Accepted Answer

Net Fre
Net Fre on 1 Dec 2021
Notice that using the fitlm function creates an object called 'LinearModel' containing the data you need (and much more). You can name that object as you wish to make it easier, so instead of just using fitlm you should do something like this:
% assume data stored as x , y
MyModel = fitlm(x,y)
slope = MyModel.Coefficients{2,1}
Rsq = MyModel.Rsquared.Ordinary
p_value = MyModel.Coefficients{2,4}
Then you can use matlab's annotation option to display your parameters on your figure.

More Answers (1)

Arpan Bhowmik
Arpan Bhowmik on 1 Dec 2021
I understand that you want to provide additional information on your plot in a text-box like element.
You can add text-box annotations in a figure using the “annotation function as follows:
annotationObj = annotation('textbox',[0.3 0.3 0.12 0.08],'String',Some text');
You can also provide the figure handle (“gcf”, or returned object from call to figure) as the first input to the function.
You can then manipulate the “Position property (vector of doubles in the example above) to position your annotation within the figure. You can position this to be outside of the plot axes as well since the values are with respect to the frame of the figure and not the plot.
Capturing the “annotationObj in the above example will allow you to interact with the Position and String properties to find the values you’ll need for your script. It is useful to remember that the Position values vary from 0 to 1 as a fraction of the parent element’s dimensions when the “Units” property is set to "normalized".
In order to programmatically format the string you need in a script, you can use the “sprintf function. Here’s an example for your use-case:
annotationText = sprintf("R-squared value: %d\nP-value: %d\nSlope: %d",rSquared,pValue,slope);
Here are some useful documentation links:
  1. annotation:
  2. sprintf:
  3. Position property in graphics objects:
You may also find this existing MATLAB Answers entry helpful for your workflow:
Here are some useful documentation-links on plotting LinearModel objects (returned by “fitlm” function):
  1. Plotting methods on LinearModel object:
  2. Plot function for LinearModel object:





Community Treasure Hunt

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

Start Hunting!