Skip to main content
 首页 » 编程设计

python之Matplotlib 自定义饼图标签和阴影

2025年02月15日10exmyth

我正在尝试使用所示示例在 Python 2.7 中生成 Matplotlib 饼图 here .这是我正在使用的代码:

import matplotlib.pyplot as plt 
 
# The slices will be ordered and plotted counter-clockwise. 
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' 
sizes = [15, 30, 45, 10] 
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] 
explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs') 
 
plt.pie(sizes, explode=explode, colors=colors, 
        autopct='%1.1f%%', shadow=True, startangle=90, radius=0.4, 
        center=(0.5,0.5), 
        frame=True, pctdistance=1.125) 
# Set aspect ratio to be equal so that pie is drawn as a circle. 
plt.axis('equal') 
 
plt.show() 

输出如下所示

我正在尝试调整一些与标签和投影相关的绘图格式,并希望获得一些帮助:

A.分数 10% 的标签距离粉色楔形的距离远大于标签 45% 距离蓝色楔形的距离。似乎有关于此的问题( 1 , 2 )但是最新的 Matplotlib 有太多的值需要解压。所以,当我使用那里的答案时:

patches, texts = plt.pie(...) 

它抛出这个错误:

ValueError: too many values to unpack 

有没有办法确保所有百分比标签与其对应的楔形等距?

B. 投影太粗(或太强)。我尝试使用 here 中的 path_effects 参数对其进行自定义使用:

plt.pie(sizes, explode=explode, colors=colors, 
        autopct='%1.1f%%', shadow=True, startangle=90, radius=0.4, 
        center=(0.5,0.5), 
        frame=True, pctdistance=1.125, 
        path_effects=[path_effects.SimpleLineShadow(), 
        path_effects.Normal()]) 

但是,我得到一个错误:

 TypeError: pie() got an unexpected keyword argument 'path_effects' 

好像有个类似的问题here ,但没有答案。有没有办法手动减小阴影的厚度?

C. 我已经指定了一个字典,其中包含我想用于饼图百分比标签的字体:

labelfont = {'fontname':'Times New Roman', 'size':'14', 'color':'black', 'weight':'bold'} 

例如,如果我想在散点图的x轴标签上使用这个,我一直在使用这个:

plt.xlabel('My_label',**labelfont) 

我正在尝试为饼图百分比标签做类似的事情。我如何指定该字体应用于百分比?

请您参考如下方法:

答:

来自mpl pie文档:

If autopct is not None, return the tuple (patches, texts, autotexts), where patches and texts are as above, and autotexts is a list of Text instances for the numeric labels.

您需要再解压一个值。所以你需要改变这一行:

patches, texts = plt.pie(...) 

对于

patches, texts, autotexts = plt.pie(...) 

乙:

因为 plt.pie 错误说没有 path_effects 参数。您可以遍历补丁并设置自定义阴影:

for patch in patches: 
    patch.set_path_effects([path_effects.SimpleLineShadow(), 
        path_effects.Normal()]) 

C:

您可以使用 plt.rc为此。