Skip to content Skip to sidebar Skip to footer

Plotting A Pie-chart In Matplotlib At A Specific Angle With The Fracs On The Wedges

I am plotting a piechart with matplotlib using the following code: ax = axes([0.1, 0.1, 0.6, 0.6]) labels = 'Twice Daily', 'Daily', '3-4 times per week', 'Once per week','Occasiona

Solution 1:

Ordinarily I wouldn't recommend changing the source of a tool, but it's hacky to fix this outside and easy inside. So here's what I'd do if you needed this to work Right Now(tm), and sometimes you do..

In the file matplotlib/axes.py, change the declaration of the pie function to

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

i.e. simply add start_angle=None to the end of the arguments.

Then add the five lines bracketed by "# 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)

Then if start_angle is None, nothing happens, but if start_angle has a value, then that's the location that the first slice (in this case the 20%) is centred on. For example,

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

produces

enter image description here

Note that in general you should avoid doing this, patching the source I mean, but there are times in the past when I've been on deadline and simply wanted something Now(tm), so there you go..

Post a Comment for "Plotting A Pie-chart In Matplotlib At A Specific Angle With The Fracs On The Wedges"