如何改善pyplot饼图中分数标签的旋转

时间:2017-04-28 15:11:31

标签: python matplotlib pie-chart

我复制了以下示例代码,但稍作修改。我想以某个角度旋转分数。我实现了目标,但我的问题是,是否有更简单的方法来旋转分数:

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

enter image description here

是否有可能改善这一点?

1 个答案:

答案 0 :(得分:3)

问题中旋转自动百分比标签的方法已经非常简单了。如果“更容易”意味着“更短”,您可以将整个命令放在一行中:

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