如何使用 matplotlib 绘制散点饼图

Che*_*eng 3 python matplotlib

我找到了绘制散点图聊天的代码示例

在此示例中,所有三个散点中每个饼图切片的大小均相同。我想知道是否可以使每个饼图都独一无二(不同的切片数量和不同的饼图比例)

Qua*_*ang 9

是的,这是完全可能的。这是一个在给定位置以给定大小绘制饼图的函数:

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
Run Code Online (Sandbox Code Playgroud)

使用该函数,我们可以绘制三个饼图:

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()
Run Code Online (Sandbox Code Playgroud)

给出:

在此输入图像描述