How can I include an equation in a scatter plot with linear regression line?

14 ビュー (過去 30 日間)
Shannon
Shannon 2013 年 2 月 24 日
Hi,
I'm trying to add the equation for a linear regression line to a scatter plot that I have made. I first plotted my data points then used the polyfit function to add a first-order line to my plot. Now I want the equation of the line in y = mx + b form to appear on my scatter plot, and I want the equation to update as I change my data points. Is there a command to help me do this?
Here's my code for adding the line:
%Find the best fit line for this data
bestfit = polyfit(Year,disp_pr_s,1);
disp_pr_s = bestfit(1)*Year + bestfit(2);
hold on
plot(Year,disp_pr_s,'k')
hold off
Thanks in advance!

採用された回答

Image Analyst
Image Analyst 2013 年 2 月 24 日
Use sprintf() to build a string. Then use text() to place it
theString = sprintf('y = %.3f x + %.3f', bestfit(1), bestfit(2));
text(x, y, theString, 'FontSize', 24);
  1 件のコメント
Shannon
Shannon 2013 年 2 月 24 日
Great, I got this to work as soon as I realized that x and y in "text(x, y, theString, 'FontSize', 24)" refer to actual coordinates dependent on my x and y axis in the original plot.
Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeInterpolation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by