Adding input variables to plot title/legend in Python

Question:

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.”

Asked By: dzejkob

||

Answers:

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)

Answered By: blue_note

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}"
Answered By: N Chauhan

The other answers didn’t work for my code, but adaption of it did. Shown below:

Showing y = m*x + c printed on the plot in log format.

a1 = coefs[0] # variable 1
a2 = coefs[1] # variable 2

message = f"log(L/Lo) = {a1} * log(M/Mo) + {a2}"

# Define axes
left = 0.01
width = 0.9
bottom  = 0.01
height = 0.9
right = left + width
top = bottom + height
ax = plt.gca()

# Transform axes
ax.set_transform(ax.transAxes)

# Define text
ax.text(0.5 * (left + right), 0.5 * (bottom + top), message,
        horizontalalignment='center',
        verticalalignment='center',
        size= 10,
        color='r',
        transform=ax.transAxes)

plt.show()

Using code from @ https://pythonguides.com/add-text-to-plot-matplotlib/

enter image description here

Answered By: Brendan Darrer
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.