更改 Matplotlib 图上的标签(例如更改为 Muli)

Changing the labels on Matplotlib graphs (for example to Muli)

所以我有以下代码:

import matplotlib.pyplot as plt
%matplotlib inline

# Following should supposedly set the font correctly:
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.serif'] = ['Muli'] + plt.rcParams['font.serif']

# create data
size_of_groups=[12,11,30,3]


colors = ['#F92969','#FACA0C','#17C37B','#D9DFEB']

# Create a pieplot
my_pie,_,texts = plt.pie(size_of_groups,radius = 1.2,colors=colors,autopct="%.1f%%",
textprops = {'color':'w',                                                                                           'size':15,                                                                                                'weight':'bold'}, pctdistance=0.75, labeldistance=0.7) #pctdistance and labeldistance change label positions.


plt.setp(my_pie, width=0.6, edgecolor='white') 
fig1 = plt.gcf()
fig1.show()

但是,运行 此代码无法获得正确的字体 (Muli)。我不能把我做错了什么:

同样适用于通过plt.text方法制作标签。

以下代码生成条形图:

import matplotlib.pyplot as plt

%matplotlib inline
import matplotlib.pyplot as plt

size_of_groups=[12,11,30,3]

colors = ['#F92969','#FACA0C','#17C37B','#D9DFEB']

plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.serif'] = ['Muli'] + plt.rcParams['font.sans-serif']
plt.rcParams['font.size'] = 15



plt.bar(height=size_of_groups,x=['a','b','c','d'],color=colors,width=0.95,label=['1',2,3,4]) #pctdistance and labeldistance change label positions.

# Setting the font to what I want it to be (Muli), using plt.text to place labels:

for v,i in enumerate(size_of_groups):
    if i > 5:
        plt.text(v-0.05,i-2.75,str(v),color='white',fontweight='bold',fontdict=None)
    if i <= 5:
        plt.text(v-0.05,i+0.8,str(v),color='gray',fontweight='bold',fontdict=None)

再一次,我得到了一个非常漂亮的图表,但字体不太正确:

所以我的问题是我似乎缺少的正是它,所以我没有看到我想要的字体。

我认为你需要确保你已经安装了 muli 作为系统字体。

要获取已安装字体的列表,您可以这样做

import matplotlib.font_manager
sorted({i.name for i in matplotlib.font_manager.fontManager.ttflist})

如果你想要的字体 (Muli) 不在那里,那么找到你的字体列表文件(对我来说这是 ~/.matplotlib/fontlist-v300.json)并删除它。再次尝试上面的命令,看看它现在是否出现了。

你可能还想

plt.rcParams['font.sans-serif'] = ['Muli'] + plt.rcParams['font.sans-serif']

(sans-serif 而不是 serif)

这样做 运行 我得到你的代码

有关字体的更多详细信息,请尝试

sorted([i for i in matplotlib.font_manager.fontManager.ttflist], key=lambda i: i.name)