简体   繁体   English

如何使用 matplotlib 绘制散点图

[英]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)我想知道是否可以使每个饼图都独一无二(不同的切片数量和不同的饼图比例)

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:给出:

在此处输入图片说明

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

输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM