[英]Color, bold in part of text in matplotlib (using LaTeX), with pdf output?
我正在使用 Python 中的 matplotlib 创建一个要保存为 PDF 的图形。 (仅)图形标题的第一个字母需要加粗和特定(自定义)颜色。 简约地说,我会假设以下内容会起作用(非自定义颜色):
fig,ax = plt.subplots(1)
ax.plot(1,1)
ax.set_title(r'{\bf\color{red} A}: absquatulate')
plt.savefig('test.pdf')
但事实并非如此。
一个可以代替(我找不到参考)去更多的麻烦,使用 PGF 后端,以获得一些颜色,但是当使用r'\bf'
时这会失败:
import matplotlib.pyplot as plt
pgf_with_latex = {
"text.usetex": True,
"pgf.rcfonts": False,
"pgf.preamble": [
r'\usepackage{color}',
r'\definecolor{colorB}{rgb}{ 0.1, 0.5, 0.999 }'
]
}
matplotlib.rcParams.update(pgf_with_latex)
fig,ax = plt.subplots(1)
ax.plot(1,1)
ax.set_title(r'{\bf\color{colorB} A}: absquatulate')
plt.savefig('test.pdf')
如何让 \bf\color 同时工作?
实际上,以下工作(使用\bfseries
,我发现它需要单独的嵌套大括号):
#!/usr/bin/python
import matplotlib
from matplotlib.backends.backend_pgf import FigureCanvasPgf
matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)
pgf_with_latex = {
"text.usetex": True,
"pgf.preamble": [
r'\usepackage{color}',
r'\definecolor{colorB}{rgb}{ 0.1, 0.5, 0.999 }'
]
}
import matplotlib
matplotlib.rcParams.update(pgf_with_latex)
import matplotlib.pyplot as plt
plt.figure(figsize=(2,2))
plt.plot(1,1)
plt.title(r'{ \textcolor{colorB} {\bfseries A}}: absquatulate')
plt.savefig('test.pdf')
CPBL优雅答案的略微更新版本。 主要区别在于较新版本的 Matplotlib 想要获取pgf.preamble
作为字符串,而不是字符串列表。 此外,似乎text.usetex
默认情况下已经是True
。
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pgf import FigureCanvasPgf
matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)
matplotlib.rcParams.update({
"pgf.preamble": r"""
\usepackage{xcolor}
\definecolor{colorB}{rgb}{ 0.1, 0.5, 0.999 }
"""
})
plt.figure(figsize=(2, 2))
plt.plot(1, 1)
plt.title(r'{ \textcolor{colorB} {\bfseries A}}: absquatulate')
plt.savefig('test.pdf')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.