Cheng
Cheng

Reputation: 17904

How to plot scatter pie chart using matplotlib

I find the code example for drawing scatter pie chat

In this example, the size of each pie slices is identical across all three scatters. I would like to know if it is possible to make each pie chart unique (different number of slices and different pie proportions)

Upvotes: 3

Views: 5586

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150745

Yes, it's totally possible. Here's a function that plot a pie chart at given position with a given size:

def draw_pie(dist, 
             xpos, 
             ypos, 
             size, 
             ax=None):
    if ax is None:
        fig, ax = plt.subplots(figsize=(10,8))

    # for incremental pie slices
    cumsum = np.cumsum(dist)
    cumsum = cumsum/ cumsum[-1]
    pie = [0] + cumsum.tolist()

    for r1, r2 in zip(pie[:-1], pie[1:]):
        angles = np.linspace(2 * np.pi * r1, 2 * np.pi * r2)
        x = [0] + np.cos(angles).tolist()
        y = [0] + np.sin(angles).tolist()

        xy = np.column_stack([x, y])

        ax.scatter([xpos], [ypos], marker=xy, s=size)

    return ax

Using that function, we can draw, say three pie charts:

fig, ax = plt.subplots(figsize=(10,8))
draw_pie([1,2,1],1,1,10000,ax=ax)
draw_pie([2,2,2,2], 2, 1, 20000, ax=ax)
draw_pie([1,1,1,1,1], 1.5,1.5, 30000, ax=ax)
plt.xlim(0.6,2.5)
plt.ylim(0.8, 1.8)
plt.show()

gives:

enter image description here

Upvotes: 9

Argysh
Argysh

Reputation: 151

you could implement it like this:

import numpy as np
import matplotlib.pyplot as plt

def drawPieMarker(xs, ys, ratios, sizes, colors):
    assert sum(ratios) <= 1, 'sum of ratios needs to be < 1'

    markers = []
    previous = 0
    # calculate the points of the pie pieces
    for color, ratio in zip(colors, ratios):
        this = 2 * np.pi * ratio + previous
        x  = [0] + np.cos(np.linspace(previous, this, 10)).tolist() + [0]
        y  = [0] + np.sin(np.linspace(previous, this, 10)).tolist() + [0]
        xy = np.column_stack([x, y])
        previous = this
        markers.append({'marker':xy, 's':np.abs(xy).max()**2*np.array(sizes), 'facecolor':color})

    # scatter each of the pie pieces to create pies
    for marker in markers:
        ax.scatter(xs, ys, **marker)


fig, ax = plt.subplots()
drawPieMarker(xs=np.random.rand(3),
              ys=np.random.rand(3),
              ratios=[.3, .2, .5],
              sizes=[80, 60, 100],
              colors=['cyan', 'orange', 'teal'])
drawPieMarker(xs=np.random.rand(2),
              ys=np.random.rand(2),
              ratios=[.33, .66],
              sizes=[100, 120],
              colors=['blue', 'yellow'])
drawPieMarker(xs=np.random.rand(2),
              ys=np.random.rand(2),
              ratios=[.33, .25],
              sizes=[50, 75],
              colors=['maroon', 'brown'])
plt.show()

output

Upvotes: 3

Related Questions