How can I improve the rotation of fraction labels in a pyplot pie chart

风流意气都作罢 提交于 2021-02-19 03:52:25

问题


I copied the following example code with a minor change. I want to rotate the fractions in a certain angle. I achived my goal but my question is if there is an easier way to rotate the fractions:

import matplotlib.pyplot as plt
import matplotlib

# Data to plot
labels = 'Python', 'C++', 'Ruby', 'Java'
sizes = [215, 130, 245, 210]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0)  # explode 1st slice

# Plot
pie_properties = plt.pie(sizes,  labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=False, startangle=140, pctdistance=0.8, radius = 0.5)

# Rotate fractions
# [0] = wedges, [1] = labels, [2] = fractions
fraction_text_list = pie_properties[2]
for text in fraction_text_list:
    text.set_rotation(315)

plt.axis('equal')
plt.show()

Is it possible to improve this?


回答1:


The method in the question to rotate the auto percentage labels is already quite easy. If by "easier" you mean "shorter", you can put the whole command in one single line:

import matplotlib.pyplot as plt

# Data to plot
labels = 'Python', 'C++', 'Ruby', 'Java'
sizes = [215, 130, 245, 210]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0)  # explode 1st slice

# Plot
w,l,p = plt.pie(sizes,  labels=labels, colors=colors,
        autopct='%1.1f%%', startangle=140, pctdistance=0.8, radius = 0.5)
[t.set_rotation(315) for t in p]

plt.axis('equal')
plt.show()


来源:https://stackoverflow.com/questions/43683513/how-can-i-improve-the-rotation-of-fraction-labels-in-a-pyplot-pie-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!