Skip to main content
 首页 » 编程设计

python之Matplotlib:设置文本族

2025年05月04日10java哥

我想更改饼图标签之一的字体和大小。 该字体称为“Berkelium Type”,根据我的 .matplotlib 目录中的 fontList.cache 文件,Matplotlib 可以加载它。

代码是

import matplotlib.pyplot as plt 
 
count  = (1., 2., 3.) 
labels = ('Text1', 'Text2', 'Text3') 
 
pie = plt.pie(count, labels=labels) 
pie[1][0].set_fontsize(24) 
pie[1][0].set_family('Berkelium Type') 
 
plt.axis('equal') 
plt.draw() 
plt.show() 

到目前为止,更改字体大小有效。但是,它并没有改变字体本身。

我用一个简单的文本做了一个测试

test = plt.text(0.5, 0.5, 'This is a test.') 

都不是

test.set_family('serif') 

也不

test.set_family('sans-serif') 

对文本有任何影响。

所以我想知道我在这里做的概念上是否有误。 这是更改文本字体的正确方法吗?

更新:

我做了什么this post建议:

import matplotlib.font_manager as fm 
import matplotlib.pyplot as plt 
 
fig, ax = plt.subplots() 
ax.plot(range(10)) 
 
prop = fm.FontProperties(fname='/home/sebastian/.local/share/font/kkberktp.ttf') 
ax.set_title('This is some random font', fontproperties=prop, size=32) 
 
plt.show() 

结果我得到了这个:

这不是我选择的字体。

是否有任何内容覆盖了我的字体设置?

字体可用here .

请您参考如下方法:

要全局更改字体,您可以使用 rcParams 进行设置.将此行放在 matplotlib 导入之后:

plt.rcParams['font.family'] = 'Berkelium Type' 

要仅更改饼图的字体,您可以使用 pie 的 textprops 选项:

pie = plt.pie(count, labels=labels, textprops={'family':'Berkelium Type'}) 

要仅将字体更改为文本对象之一,您可以使用 update:

pie[1][0].update({'family':'Berkelium Type'})