Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styling part of label in legend in matplotlib

Is it possible to have part of the text of a legend in a particular style, let's say, bold or italic?

like image 488
englebip Avatar asked Dec 04 '11 15:12

englebip


People also ask

How do I fix the legend position in Matplotlib?

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.

How do I label a specific point in Matplotlib?

To label the scatter plot points in Matplotlib, we can use the matplotlib. pyplot. annotate() function, which adds a string at the specified position.


2 Answers

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() 
like image 194
Homayoun Hamedmoghadam Avatar answered Sep 19 '22 13:09

Homayoun Hamedmoghadam


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

enter image description here

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

like image 44
joris Avatar answered Sep 19 '22 13:09

joris