Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib, including more than one defined variable on legend label

Im trying to include two or more variables, previously defined in the code, to the label for the legend or when plotting text. For example, I have a bunch of functions plotted and I want the equations for each on the legend. If I just have something like y = Ax, where A is found by fitting a function to some data I would write something like:

 plt.plot(x, y, label='y = %.2f x' %A) 

and on the legend I would see the real value of A on the equation. Now if I want to do the same with y = Ax + B and I go

 plt.plot(x, y, label='y = %.2f x + %.2f' %A %B)

I get an error. Most of the ways I tried gave me syntax error and I got one that said not enough arguments for format string.

like image 688
jp_astro104 Avatar asked Nov 19 '15 06:11

jp_astro104


2 Answers

Try this

 plt.plot(x, y, label='y = %.2f x + %.2f' %(A, B))
like image 139
Mangu Singh Rajpurohit Avatar answered Oct 21 '22 07:10

Mangu Singh Rajpurohit


As an alternative, you can use the more flexible python string formatting using the .format() method. For example:

 plt.plot(x, y, label='y = {0:.2f} x + {1:.2f}'.format(A,B))
like image 39
tmdavison Avatar answered Oct 21 '22 08:10

tmdavison