双标题数据帧散点图

2024-05-15 12:40:15 发布

您现在位置:Python中文网/ 问答频道 /正文

具有如下结构的数据帧:

                 A            B
country       C     D     C      D
Albany      2.05    4    1.85    4
China       2.67    3    1.21    3
Portugal    1.44    6    2.34    6
France      5.83    3    2.50    3
Greece      0.63    6    3.02    6

我不知道如何绘制散点图,在散点图中,选择a或B,可以得到每个国家x=C和y=D的散点图。如果我这样做,它会给我一个关键错误:

df.plot.scatter(x='C', y='D')

有什么建议吗

非常感谢


Tags: 数据dfplot错误绘制国家结构country
1条回答
网友
1楼 · 发布于 2024-05-15 12:40:15

可以在第0级列上group分别绘制每个列。分组只会分割数据帧,它不会修改任何内容,因此您可以使用元组作为键,或者使用DataFrame.xs删除现在冗余的多索引级别

for idx, gp in df.groupby(level=0, axis=1):
    gp.xs(idx, level=0, axis=1).plot.scatter(x='C', y='D', title=idx)

enter image description hereenter image description here


或者,如果您想要一个绘图:

import matplotlib.pyplot as plt

cd = {'A': 'red', 'B':'blue'}  # color by group

fig, ax = plt.subplots()
for idx, gp in df.groupby(level=0, axis=1):
    gp.xs(idx, level=0, axis=1).plot.scatter(x='C', y='D', ax=ax, label=idx, c=cd[idx])

enter image description here

相关问题 更多 >