在matplotlib中以特定角度绘制饼图

2024-09-30 10:41:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用matplotlib绘制一个piechart,使用以下代码:

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

这将生成以下饼图。 PieChart 1

不过,我想在饼图的开头加上第一个楔子,我能找到的唯一解决方案是使用this code

不过,在如下使用时

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

这将生成以下饼图

enter image description here

但是,这不会像前面的饼图那样在楔块上打印分形。我试过一些不同的方法,但是我不能保留这些缺点。如何在中午开始第一个楔子,并在楔子上显示裂缝??


Tags: fromimportlabelsmatplotlibpltaxlabeldaily
1条回答
网友
1楼 · 发布于 2024-09-30 10:41:03

一般来说,我不建议更改工具的源代码,但在外部修复和内部轻松修复这一问题是很麻烦的。如果你现在需要这个,我会这样做,有时你会这样做。。

在文件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

然后加上用“加法”括起来的五行。

    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)

产生

enter image description here

请注意,一般来说,你应该避免这样做,修补源代码,我的意思是,但在过去的一些时间里,我已经到了最后期限,只是想要一些东西现在(tm),所以你去。。

相关问题 更多 >

    热门问题