How to plot a pie chart with the first wedge on top, in Python? [matplotlib]

主宰稳场 提交于 2019-12-06 09:57:09

问题


How can a pie chart be drawn with Matplotlib with a first wedge that starts at noon (i.e. on the top of the pie)? The default is for pyplot.pie() to place the first edge at three o'clock, and it would be great to be able to customize this.


回答1:


Just because this came up in a Google search for me, I'll add that in the meantime, matplotlib has included just this as an additional argument to the pie function.

Now, one can call plt.pie(data, start_angle=90) to have the first wedge start at noon.

PyPlot documentation on this




回答2:


It's a bit of a hack, but you can do something like this...

import matplotlib.pyplot as plt
from matplotlib.transforms import Affine2D
import numpy as np

x = [5, 20, 10, 10]
labels=['cliffs', 'frogs', 'stumps', 'old men on tractors']

plt.figure()
plt.suptitle("Things I narrowly missed while learning to drive")
wedges, labels = plt.pie(x, labels=labels)
plt.axis('equal')

starting_angle = 90
rotation = Affine2D().rotate(np.radians(starting_angle))

for wedge, label in zip(wedges, labels):
    label.set_position(rotation.transform(label.get_position()))
    if label._x > 0:
        label.set_horizontalalignment('left')
    else:
        label.set_horizontalalignment('right')

    wedge._path = wedge._path.transformed(rotation)

plt.show()



来源:https://stackoverflow.com/questions/3816809/how-to-plot-a-pie-chart-with-the-first-wedge-on-top-in-python-matplotlib

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