[英]Avoid specifying font family in PGF export of matplotlib figure
我將 matplotlib 圖形導出為 PGF 以在 LaTeX 中使用。
將圖形保存為 PGF 時,matplotlib 似乎向每個文本條目(軸標簽、刻度、圖例條目、注釋)添加了\\sffamily
附加項。 這將阻止它從全局文檔字體正確繼承字體。
如果文本來自同一個家族,文本可以從全局文檔字體中繼承字體,但如果全局字體來自不同的家族,它將恢復為默認的 sffamily 字體。
我相信我已經隔離了這個問題:如果我編輯 PGF 文檔並簡單地刪除任何文本條目的\\sffamily
部分,問題不再存在並且全局字體被繼承。 刪除不會阻止 LaTeX 正確編譯它,並且我沒有收到任何錯誤。
由於上述發現,我認為問題與rcParams
或任何 LaTeX 序言(無論是在 python 中還是在實際的 LaTeX 文檔中)無關。
我只是在最簡單的情節上進行了嘗試,並且能夠重現該問題:
import matplotlib.pyplot as plt
fig = plt.figure()
plt.xlabel('a label')
fig.savefig('fig.pgf')
並且 pgf 文檔將包含以下行:
\pgftext[x=3.280000in,y=0.240809in,,top]{\color{textcolor}\sffamily\fontsize{10.000000}{12.000000}\selectfont a label}%
所以添加了\\sffamily
。 在 LaTeX 中渲染它會強制使用 sans-serif 字體。 刪除\\sffamily
並渲染它將允許它繼承字體系列。
有沒有辦法避免在 matplotlib 的 PGF 輸出中包含字體系列?
我無法提供解決方案,只能提供基於 @samcarter 評論的解決方法:您可以在本地重新定義\\sffamily
,例如:
\documentclass{article}
\usepackage{pgf}
\usepackage{fontspec}
\setmainfont{DejaVu Serif}
\setsansfont{DejaVu Sans}
\setmonofont{DejaVu Sans Mono}
\begin{document}
Lorem ipsum {\sffamily Lorem ipsum}
\begin{center}
\renewcommand\sffamily{}
\input{fig.pgf}
\end{center}
Lorem ipsum {\sffamily Lorem ipsum}
\end{document}
您可以使用任何環境或\\begingroup
和\\endgroup
\\begingroup
而不是center
。
在將 pgf 文件導入 tex 文檔之前,還有另一種解決方法是用sed替換字體規范。
\documentclass{article}
\usepackage{pgf}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}
\usepackage{filecontents}
\begin{document}
\begin{figure}
\begin{filecontents*}{tmpfile.sed}
# sed command file
s/\\color{textcolor}\\sffamily\\fontsize{.*}{.*}\\selectfont //\end{filecontents*}
\immediate\write18{sed -i -f tmpfile.sed yourplot.pgf}
\import{yourplot.pgf}
\end{figure}
\end{document}
建立在https://matplotlib.org/users/pgf.html#font-specification 上,您可以使用:
import matplotlib as mpl
import matplotlib.pyplot as plt
pgf_with_rc_fonts = {
"font.family": "serif",
}
mpl.rcParams.update(pgf_with_rc_fonts)
fig = plt.figure()
plt.xlabel('a label')
fig.savefig('fig.pgf')
這樣\\rmfamily
代替\\sffamily
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.