【问题标题】:How to avoid keys with zero percentage in pie plot matplotlib如何避免饼图matplotlib中百分比为零的键
【发布时间】:2016-12-01 19:50:33
【问题描述】:

我必须用 %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()

我的图表是

使标签成为dictant或删除小的%age键的解决方案是什么

【问题讨论】:

  • 我们应该提到饼图是邪恶的吗?
  • 问简单的问题胜于投入

标签: python matplotlib plot


【解决方案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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    相关资源
    最近更新 更多