简体   繁体   English

matplotlib中图例中标签的样式部分

[英]Styling part of label in legend in matplotlib

是否可以使用特定样式的图例文本的一部分,例如粗体斜体

As silvado mentions in his comment, you can use LaTeX rendering for more flexible control of the text rendering.正如 silvado 在他的评论中提到的,您可以使用 LaTeX 渲染来更灵活地控制文本渲染。 See here for more information: http://matplotlib.org/users/usetex.html有关更多信息,请参见此处: 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.注意标签字符串前的“r”。 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 ).因此, \\ 将被视为乳胶命令,而不是像 python 那样解释(因此您可以键入\\textbf而不是\\\\textbf )。

Write between '$$'to force matplotlib to interpret it.在 '$$' 之间写入以强制 matplotlib 解释它。

import matplotlib.pyplot as plt

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

Adding more options to the above answer by fixing the issues with that answer, with OO interface not just the state-based pyplot interface, possibility to have spaces as part of the text, boldface option in addition to italics :通过修复该答案的问题,为上述答案添加更多选项, 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
         )

For italicized title with space in between replace the above title with,对于中间有空格的斜体标题,将上面的title替换为,

 title="$\\it{ITALICIZED\ TITLE}$",

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM