Reputation: 2026
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
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
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()
Upvotes: 3
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