Reputation: 211
Hi I'm trying to enable bold font for labels in Matplotlib with Latex text rendering. I am able to do this for numerical variables (integers, floats) but failed with string variable.
So this works:
a = 1
plt.plot(X, y, label=r'\textbf{}'.format(a))
but this doesn't:
a = 'text'
plt.plot(X, y, label=r'\textbf{}'.format(a))
I know I can do this:
plt.plot(X, y, label=r'\textbf{text}')
But how can I use the format for a string variable?
Thanks!
Upvotes: 1
Views: 2418
Reputation: 339170
You need to escape the curly brackets of the latex command, since the .format
function uses those brackets to determine where to put its argument in the text.
Consider e.g.
r'\textbf{}'.format("something")
which results in
"\textbfsomething"
This is of course no valid latex command. On the other hand
r'\textbf{}'.format(9)
results in
"\textbf9"
which is a valid latex command. To be on the save side, always escape all curly brackets.
import matplotlib.pyplot as plt
plt.rcParams["text.usetex"] = True
a = 1
plt.plot([1,2], [2,3], label=r'\textbf{{{}}}'.format(a))
a = 'text'
plt.plot([1,2], [1,2], label=r'\textbf{{{}}}'.format(a))
plt.legend()
plt.show()
Upvotes: 2