在matplotlib图例中为标签部分设置样式
有没有办法让图例中的一部分文字用特定的样式,比如说加粗或者斜体?
3 个回答
6
在上面的回答中增加更多选项,解决了那个回答中的一些问题,使用面向对象的接口,而不仅仅是基于状态的pyplot接口。这样可以在文本中包含空格,还增加了加粗的选项,除了斜体之外:
ax.legend(handles=legend_handles,
labels=legend_labels,
loc='upper right',
shadow=True,
fancybox=True,
facecolor='#C19A6B',
title="$\\bf{BOLDFACED\ TITLE}$", # to boldface title with space in between
prop={'size': 12, 'style': 'italic'} # properties for legend text
)
如果想要带有空格的斜体标题,可以把上面的title
替换为:
title="$\\it{ITALICIZED\ TITLE}$",
60
在$$
之间写内容,可以强制matplotlib去理解这些内容。
import matplotlib.pyplot as plt
plt.plot(range(10), range(10), label = "Normal text $\it{Italics}$")
plt.legend()
plt.show()
44
正如silvado在他的评论中提到的,你可以使用LaTeX来更灵活地控制文本的显示效果。想了解更多信息,可以查看这里:http://matplotlib.org/users/usetex.html
下面是一个例子:
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()
注意标签字符串前面的'r'。因为有了这个,反斜杠(\)会被当作LaTeX命令来处理,而不是像Python那样解释(所以你可以直接输入\textbf
,而不是\\textbf
)。