How to add equation of a line onto a plot in python

matplotlib, numpy, python

Solution

Use `plt.text`. As the docs show, you can specify the location of the text in axis coordinates using:

text(0, 1,'matplotlib', horizontalalignment='center',
     verticalalignment='center',
     transform=ax.transAxes)

(0,0) indicates the lower-left corner, and (1,1) the upper right. So (0,1) is the upper-left corner.

To understand more about `transform=ax.transAxes`, see the transforms tutorial.

Problem

I am trying to plot a graph, add a line of best fit and display the equation of best fit on the graph. This is what I have so far but I am not sure if my method to plot the equation is correct. Can you help me? ``` plt.close("all") data = np.genfromtxt('plotfile.csv',delimiter=',', dtype = float, skiprows=1) x = data[:,1] y = data[:,2] (m,b)=polyfit(x ,y ,1) yp = polyval([m,b],x) equation = 'y = ' + str(round(m,4)) + 'x' ' + ' + str(round(b,4)) scatter(x,y) plot(x,yp) text(1,1, equation) ``` I am looping through several files to plot these graphs so always want the equation to be printed in the top corner. As the different graphs have different axis values the equation doesn't always plot in the same position or doesn't always plot on the graph if its off the scale. How can I make the equation always display in the same place regardless of the axis values?

Original source