Search code examples
pythonmatplotlibpie-chart

Matplotlib: Draw pie chart with wedge breakdown into barchart


I've got a pie chart (example) with following fracs = [10, 20, 50, 30]. Drawing this with matplotlib is no problem. How do I get a breakdown of the first wedge (10) into 6 and 4? Ideally, I want a second wedge for the 20, to breakdown into 10, 3, 7. This would be displayed as a barchart near the specific wedge or a pie chart (which would make it a pie of pie chart similar to the ones in Excel).


Solution

  • Here is one way of doing it (possibly not the best...). I've adapted some of the code found here, on the matplotlib site to make a little_pie function, that will draw small pie charts at arbitrary positions.

    from pylab import *
    import math
    import numpy as np
    
    def little_pie(breakdown,location,size):
        breakdown = [0] + list(np.cumsum(breakdown)* 1.0 / sum(breakdown))
        for i in xrange(len(breakdown)-1):
            x = [0] + np.cos(np.linspace(2 * math.pi * breakdown[i], 2 * math.pi *    
                              breakdown[i+1], 20)).tolist()
            y = [0] + np.sin(np.linspace(2 * math.pi * breakdown[i], 2 * math.pi * 
                              breakdown[i+1], 20)).tolist()
            xy = zip(x,y)
            scatter( location[0], location[1], marker=(xy,0), s=size, facecolor=
                   ['gold','yellow', 'orange', 'red','purple','indigo','violet'][i%7])
    
    figure(1, figsize=(6,6))
    
    little_pie([10,3,7],(1,1),600)
    little_pie([10,27,4,8,4,5,6,17,33],(-1,1),800)
    
    fracs = [10, 8, 7, 10]
    explode=(0, 0, 0.1, 0)
    pie(fracs, explode=explode, autopct='%1.1f%%')
    show()
    

    enter image description here