Python 如何避免饼图matplotlib中的键百分比为零
我必须用%age值绘制饼图,我面临一个问题,即一些值非常小,它们的%age大约为零,当我在python中使用matplotlib绘制时,它们的标签覆盖了,并且它们不可读。我认为它的一个解决方案是避免使用0%年龄的值,第二个解决方案是分离标签以重叠(使用一些箭头等)。这是我的简单代码Python 如何避免饼图matplotlib中的键百分比为零,python,matplotlib,plot,Python,Matplotlib,Plot,我必须用%age值绘制饼图,我面临一个问题,即一些值非常小,它们的%age大约为零,当我在python中使用matplotlib绘制时,它们的标签覆盖了,并且它们不可读。我认为它的一个解决方案是避免使用0%年龄的值,第二个解决方案是分离标签以重叠(使用一些箭头等)。这是我的简单代码 def show_pi_chart(plot_title,keys,values,save_file): size = len(keys) #Get Colors list color_lis
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))
我们应该提到饼图是邪恶的吗?与其全神贯注,不如问一个简单的问题