Skip to main content
 首页 » 编程设计

python之Matplotlib 为所有图勾选无衬线字体

2024年12月31日9开发

我正在尝试使用 pgf 在 matplotlib 中实现无衬线轴标签和刻度。我想通过 rcParams 控制它,所以我让它适用于所有后续图。目前,我正在使用

"pgf.rcfonts":False, 
"pgf.texsystem": "pdflatex",    
"text.usetex": True,                 
"font.family": "sans-serif", 

我从 mpl 文档改编而来。它确实将我在图中的所有文本设置为无衬线字体。但是,数字保留为衬线字体。我希望它们是无衬线字体。一旦我强制格式化程序,它就是无衬线字体。有什么办法让它自动执行? MinEx 跟随...

import matplotlib as mpl 
import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.ticker import FormatStrFormatter 
 
#define style 
style = { 
        "pgf.rcfonts":False, 
        "pgf.texsystem": "pdflatex",    
        "text.usetex": True,                 
        "font.family": "sans-serif" 
        } 
#set 
mpl.rcParams.update(style) 
 
#get data 
data = np.random.random(100) 
#set up plot 
f,ax = plt.subplots() 
ax.plot(data) 
#label something 
ax.set_xlabel('Runner') 

标签现在没有了。蜱虫不是!但是打电话的时候

ax.xaxis.set_major_formatter(FormatStrFormatter('%d')) 

他们是。

请您参考如下方法:

根据pgf texsystem example ,您需要使用“pfg”后端 (mpl.use("pgf")) 并选择您要使用的字体:

style = { 
        "pgf.texsystem": "pdflatex",    
        "text.usetex": True,                 
        "pgf.preamble": [ 
         r"\usepackage[utf8x]{inputenc}", 
         r"\usepackage[T1]{fontenc}", 
         r"\usepackage{cmbright}", 
         ] 
        } 

或者,您可以使用格式化程序,它不会将刻度标签格式化为 latex 数学(即不会将它们放入美元符号中)。

可以通过设置使默认的 ScalarFormatter 不使用 latex 数学

ax.xaxis.get_major_formatter()._usetex = False 
ax.yaxis.get_major_formatter()._usetex = False