【发布时间】:2012-01-12 15:55:16
【问题描述】:
是否可以将图例的部分文本采用特定样式,比如粗体或斜体? p>
【问题讨论】:
-
您是否尝试过 tex 格式是否适用于图例?
标签: python matplotlib text customization legend
是否可以将图例的部分文本采用特定样式,比如粗体或斜体? p>
【问题讨论】:
标签: python matplotlib text customization legend
正如 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”。因此,\ 将被视为乳胶命令,而不是像 python 那样解释(因此您可以输入 \textbf 而不是 \\textbf)。
【讨论】:
texlive(我有 texlive-base)和 texlive-latex-extra 软件包之前无法在 Ubuntu 11.10 中运行示例代码。
texlive、texlive-latex-extra 和 dvipng 才能使此示例正常运行。
cm-super;所以现在需要的整个软件包列表如下,在一个安装命令中:sudo apt-get install dvipng texlive-latex-extra texlive-fonts-recommended cm-super
在 '$$' 之间写入以强制 matplotlib 对其进行解释。
import matplotlib.pyplot as plt
plt.plot(range(10), range(10), label = "Normal text $\it{Italics}$")
plt.legend()
plt.show()
【讨论】:
\bf 而不是 \it。
\ (反斜杠空格)在数学模式中插入一个空格。 $这些\是\字$。 $\mathrm{whatever}$ 也很有用。
通过修复该答案的问题,为above answer 添加更多选项,OO 界面不仅仅是基于状态的 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}$",
【讨论】: