2

我正在使用以下代码使用 matplotlib 绘制饼图:

ax = axes([0.1, 0.1, 0.6, 0.6])
labels = 'Twice Daily', 'Daily', '3-4 times per week', 'Once per week','Occasionally'
fracs = [20,50,10,10,10]

explode=(0, 0, 0, 0,0.1)
patches, texts, autotexts = ax.pie(fracs, labels=labels, explode = explode,         
                             autopct='%1.1f%%', shadow =True)
proptease = fm.FontProperties()
proptease.set_size('xx-small')
setp(autotexts, fontproperties=proptease)
setp(texts, fontproperties=proptease)
rcParams['legend.fontsize'] = 7.0
savefig("pie1")

这将产生以下饼图。 饼图 1

但是,我想从顶部的第一个楔形开始饼图,我能找到的唯一解决方案是使用此代码

但是,如下使用它,

from pylab import *
from matplotlib import font_manager as fm
from matplotlib.transforms import Affine2D
from matplotlib.patches import Circle, Wedge, Polygon
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

labels = 'Twice Daily', 'Daily', '3-4 times per week', 'Once per week','Occasionally'
fracs = [20,50,10,10,10]

 wedges, plt_labels = ax.pie(fracs, labels=labels)
 ax.axis('equal')

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

for wedge, label in zip(wedges, plt_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.savefig("pie2")

这将产生以下饼图

在此处输入图像描述

但是,这不会像之前的饼图中那样在楔形上打印分数。我尝试了一些不同的东西,但我无法保留碎片。我怎样才能在中午开始第一个楔子并在楔子上显示碎片?

4

1 回答 1

2

通常我不建议更改工具的来源,但是在外部修复它并且在内部很容易解决这个问题。因此,如果您现在需要此功能(tm),这就是我会做的事情,有时您会这样做..

在该文件matplotlib/axes.py中,将 pie 函数的声明更改为

def pie(self, x, explode=None, labels=None, colors=None,
        autopct=None, pctdistance=0.6, shadow=False,
        labeldistance=1.1, start_angle=None):

即简单地添加start_angle=None到参数的末尾。

然后添加用“#addition”括起来的五行。

    for frac, label, expl in cbook.safezip(x,labels, explode):
        x, y = center
        theta2 = theta1 + frac
        thetam = 2*math.pi*0.5*(theta1+theta2)

        # addition begins here
        if start_angle is not None and i == 0:
            dtheta = (thetam - start_angle)/(2*math.pi)
            theta1 -= dtheta
            theta2 -= dtheta
            thetam = start_angle
        # addition ends here

        x += expl*math.cos(thetam)
        y += expl*math.sin(thetam)

然后,如果 start_angle 为 None,则什么也不会发生,但如果 start_angle 有一个值,那么这就是第一个切片(在本例中为 20%)的中心位置。例如,

patches, texts, autotexts = ax.pie(fracs, labels=labels, explode = explode,         
                             autopct='%1.1f%%', shadow =True, start_angle=0.75*pi)

生产

在此处输入图像描述

请注意,一般情况下,您应该避免这样做,修补我的意思是源代码,但过去有时我已经到了截止日期,只是现在想要一些东西(tm),所以你去..

于 2012-02-10T01:23:37.337 回答