Skip to main content
 首页 » 编程设计

python之如何避免饼图 matplotlib 中百分比为零的键

2025年02月15日14落叶无声

我必须用 %age 值绘制饼图,我面临一个问题,即某些值非常小,它们的 %age 大约为零,当我在 python 中使用 matplotlib 进行绘图时,它们的标签重叠并且不可读。我认为它的一个解决方案是避免 %age 为零的值,其次是将标签分开以重叠(用一些箭头等)。这是我的简单代码

def show_pi_chart(plot_title,keys,values,save_file): 
    size = len(keys) 
    #Get Colors list 
    color_list = make_color_list(size) 
    pyplot.axis("equal") 
    pyplot.pie(values, 
               labels=keys, 
               colors=color_list, 
               autopct="%1.1f%%" 
               ) 
    pyplot.title(plot_title)   
    pyplot.show() 

我的图表是

有什么解决方案可以使标签听写或删除小的 %age 键

请您参考如下方法:

以下代码应按预期工作:

from matplotlib import pyplot 
from collections import Counter 
import numpy as np 
 
def fixOverLappingText(text): 
 
    # if undetected overlaps reduce sigFigures to 1 
    sigFigures = 2 
    positions = [(round(item.get_position()[1],sigFigures), item) for item in text] 
 
    overLapping = Counter((item[0] for item in positions)) 
    overLapping = [key for key, value in overLapping.items() if value >= 2] 
 
    for key in overLapping: 
        textObjects = [text for position, text in positions if position == key] 
 
        if textObjects: 
 
            # If bigger font size scale will need increasing 
            scale = 0.05 
 
            spacings = np.linspace(0,scale*len(textObjects),len(textObjects)) 
 
            for shift, textObject in zip(spacings,textObjects): 
                textObject.set_y(key + shift) 
 
 
def show_pi_chart(plot_title,keys,values): 
 
    pyplot.axis("equal") 
 
    # make sure to assign text variable to index [1] of return values 
    text = pyplot.pie(values, labels=keys, autopct="%1.1f%%")[1] 
 
    fixOverLappingText(text) 
    pyplot.title(plot_title) 
 
    pyplot.show() 
 
 
show_pi_chart("TITLE",("One","Two","Three","Four","Five","Six","Seven", "Eight"),(20,0,0,10,44,0,0,44))