1

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))

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.