Is it possible to have part of the text of a legend in a particular style, let's say, bold or italic?
To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.
To label the scatter plot points in Matplotlib, we can use the matplotlib. pyplot. annotate() function, which adds a string at the specified position.
Write between $$
to force matplotlib to interpret it.
import matplotlib.pyplot as plt plt.plot(range(10), range(10), label = "Normal text $\it{Italics}$") plt.legend() plt.show()
As silvado mentions in his comment, you can use LaTeX rendering for more flexible control of the text rendering. See here for more information: http://matplotlib.org/users/usetex.html
An example:
import numpy as np import matplotlib.pyplot as plt from matplotlib import rc # activate latex text rendering rc('text', usetex=True) x = np.arange(10) y = np.random.random(10) z = np.random.random(10) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y, label = r"This is \textbf{line 1}") ax.plot(x, z, label = r"This is \textit{line 2}") ax.legend() plt.show()
Note the 'r' before the strings of the labels. Because of this the \ will be treated as a latex command and not interpreted as python would do (so you can type \textbf
instead of \\textbf
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With