散点图 Python Pandas

问题描述

“散点图”(使用饼图而不是点的散点图)。我需要这样做,因为我必须表示数据的 3 个维度。 1:x轴(0-6) 2: y 轴 (0-6) 3:类别可以说(A,B,C - H)

如果两个 x 和 y 值相同,我希望饼图位于代表该类别的位置。 类似于此链接中看到的图表: https://matplotlib.org/gallery/lines_bars_and_markers/scatter_piecharts.html#sphx-glr-gallery-lines-bars-and-markers-scatter-piecharts-py

或者这张来自 Tableu图片: [![在此处输入图片描述][1]][1]

由于我只能使用 python,我一直在努力操纵代码来为我工作。 有人能帮我解决这个问题吗?非常感谢!

示例数据:

XVAL    YVAL    GROUP
1.3      4.5    A
1.3      4.5    B
4          2    E
4          6    A
2          4    A
2          4    B
1          1    G
1          1    C
1          2    B
1          2    D
3.99    4.56    G

最终输出应该在 X & Y 上有 6 个饼图,其中 1 个包含 3 个组,2 个包含 3 个组。

我的尝试:

import pandas as pd 
import matplotlib.pyplot as plt
import numpy as np

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

fig,ax = plt.subplots(figsize=(40,40))
draw_pie([Group],'xval','yval',10000,ax=ax)
draw_pie([Group],20000,30000,ax=ax)
plt.show()

解决方法

我不知道如何获得 6 个饼图。如果我们对 XVALYVAL 进行分组,则有 7 个唯一对。你可以在这条线上做一些事情:

fig,ax = plt.subplots(figsize=(40,40))
for (x,y),d in df.groupby(['XVAL','YVAL']):
    dist = d['GROUP'].value_counts()
    draw_pie(dist,x,y,10000*len(d),ax=ax)
plt.show()

输出:

enter image description here