【问题标题】:Styling part of label in legend in matplotlib在 matplotlib 中为图例中的标签部分设置样式
【发布时间】:2012-01-12 15:55:16
【问题描述】:

是否可以将图例的部分文本采用特定样式,比如粗体斜体? p>

【问题讨论】:

  • 您是否尝试过 tex 格式是否适用于图例?

标签: python matplotlib text customization legend


【解决方案1】:

正如 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 中运行示例代码。
  • 在 Ubuntu 12.04 上,我需要 texlivetexlive-latex-extradvipng 才能使此示例正常运行。
  • 在最新版本的 Ubuntu 19.10 上还需要cm-super;所以现在需要的整个软件包列表如下,在一个安装命令中:sudo apt-get install dvipng texlive-latex-extra texlive-fonts-recommended cm-super
【解决方案2】:

在 '$$' 之间写入以强制 matplotlib 对其进行解释。

import matplotlib.pyplot as plt

plt.plot(range(10), range(10), label = "Normal text $\it{Italics}$")
plt.legend()
plt.show()

【讨论】:

  • 这确实比接受的答案容易得多,并且不需要安装乳胶。对于粗体文本,请使用 \bf 而不是 \it
  • @homayoun \it 工作正常,但 \bf 没有。我有一个指向文档的链接在哪里?还有什么其他的\handles?
  • @dmeu 表示粗体应该是 \\bf(双斜杠)
  • 不适用于句子:单词之间的空格消失了,因为此功能适用于数学,而不是文本。您必须分别将每个单词加粗/斜体。
  • 使用\ (反斜杠空格)在数学模式中插入一个空格。 $这些\是\字$。 $\mathrm{whatever}$ 也很有用。
【解决方案3】:

通过修复该答案的问题,为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}$",

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多