Adding input variables to plot title/legend in Python
Solution 1
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}"
Solution 2
In python 3.6+ you can do it by prefixing the string with f
, and putting the variable in curly brackets. For earlier python version there have been various ways of doing it, look up string formatting
message = f"The slope is {m}"
plt.text(message)
(by the way, gradient is usually called slope when referring to single variable linear equation)
Admin
Updated on June 07, 2022Comments
-
Admin almost 2 years
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."