2016-12-01 97 views
1

我必须使用%年龄值绘制饼图,我正面临一个问题,即某些值非常小,其年龄大约为零,当我使用matplotlib绘制Python,therir标签重叠,他们不可读。我认为它的一个解决方案是为了避免与零%年龄和第二个值是seprate标签重叠(有一些箭头等),这里是我的简单的代码如何避免在饼图中使用零百分比的键matplotlib

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() 

我的图表是 enter image description here

是什么力量让标签dictant或删除小型%年龄键

+1

我们应该提到饼图是邪恶的吗? – percusse

+0

最好问问简单问题而不是专注 – Shafiq

回答

1

下面的代码应该工作的解决方案,旨在:

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)) 

enter image description here

相关问题