[英]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.