Search code examples
pythonmatplotlibtextlegend

Adding input variables to plot title/legend in Python


I would like to display the current value of a parameter used to plot a certain function in the plot title/legend/annotated text. As a simple example, let's take a straight line:

import numpy
import matplotlib.pyplot as plt

def line(m,c):
   x = numpy.linspace(0,1)
   y = m*x+c
   plt.plot(x,y)
   plt.text(0.1, 2.8, "The gradient is" *the current m-value should go here*)
   plt.show()

print line(1.0, 2.0)

In this case, I would like my text to say "The gradient is 1.0", but I'm not sure what the syntax is. Moreover, how would I include the second (and more) parameter(s) below, so that it reads:

"The gradient is 1.0

The intercept is 2.0."


Solution

  • Use string formatting with the .format() method:

    plt.text(0.1, 2.8, "The gradient is {}, the intercept is {}".format(m, c))
    

    Where m and c are the variables you want to substitute in.

    You can directly write the variables like this in Python 3.6+ if you prefix the string with an f whcih denotes a formatted string literal:

    f"the gradient is {m}, the intercept is {c}"