Graeme
Graeme

Reputation: 351

How can I display the formula/expression of a lm result in a plot in R?

For example, if I was to plot a trendline in Excel I can choose to include its formula on the chart, it will display something like myY = 0.5 + 0.5 * myX.

R has quite advanced functionality for creating sophisticated mathematical expressions, so I assume this is fairly straightforward to do. I'm just not sure how to do it.

Upvotes: 0

Views: 183

Answers (1)

Nick Stauner
Nick Stauner

Reputation: 393

I like to do this in the legend, so here's how I do that:

plot(myX,myY);fit=lm(myY~myX);abline(fit);fit2=round(fit[[1]],3)
legend('bottomright',lty=1,paste('myY =',feet[1],if(feet[2]>0)'+'else'-',abs(feet[2]),'myX'))

Using this dataset, here's how it looks:

You may have to change 'bottomright' depending on where you have a free corner in the scatterplot, or you may need to supply coordinates to put it outside the box if you don't have any free room for the legend inside the plot. You may also prefer to use ggplot2, in which case the code would be different...

Upvotes: 1

Related Questions