mdcq
mdcq

Reputation: 2026

Pyplot label math mode string formatting

I want to write a mathematical expression in a pyplot label and inside this expression I want to use values of variables. It should look like this

enter image description here

I thought this could maybe done with string formatting. But the following doesn't work

values = np.array([0.123, 1.234])
plt.plot(x, y, label='best fit curve $y={0:.2f}x+{1:.2f}$'.format(values))

Upvotes: 1

Views: 2404

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339092

There are two placeholders in the string to be formatted. But you supply a single value via the format method.
Instead you need to supply as many arguments as you have placeholders. In this case where you have a tuple/an array of values, you may simply unpack it, .format(*values).

import numpy as np
import matplotlib.pyplot as plt

values = np.array([0.123, 1.234])
plt.plot([0], [1], label='best fit curve $y={0:.2f}x+{1:.2f}$'.format(*values))
plt.legend()
plt.show()

enter image description here

Upvotes: 3

Uvar
Uvar

Reputation: 3462

If you use the splat operator on your values iterable, then I guess it should work fine?

plt.plot(x, y, label='best fit curve $y={0:.2f}x+{1:.2f}$'.format(*values))

Upvotes: 1

Related Questions