Reputation: 8680
I have to plot pie chart with %age values, I am facing a problem that some value are very small and their %age is about zero, when I plot using matplotlib in python, therir labels overlab and they are not readable. I think its one solution is to avoid values with zero %age and second is to seprate labels to overlap (with some arrow etc.) Here is my simple code
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()
What is the solution to make labels dictant or remove small %age keys
Upvotes: 4
Views: 3425
Reputation: 392
The following code should work as intended:
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))
Upvotes: 1