python - 如何选择哪个多索引轴将 groupby 对象中的数据拆分到不同的子图中?

标签 python matplotlib pandas

我正在使用一个 pandas.groupby 对象,我已向该对象应用了如下函数:

x = data.groupby(['congruent', 'contrast']).apply(lambda s: s.mean())[['cresp1', 'cresp2']]

打印 x 的输出:

                      cresp1    cresp2
congruent contrast                    
False     1.0       0.423077  0.442308
          2.0       0.537037  0.481481
          2.5       0.576923  0.634615
          3.0       0.568182  0.500000
          3.5       0.675000  0.750000
          4.0       0.687500  0.604167
          5.0       0.687500  0.875000
          10.0      0.869565  0.913043
True      1.0       0.568182  0.386364
          2.0       0.547619  0.500000
          2.5       0.522727  0.477273
          3.0       0.557692  0.634615
          3.5       0.571429  0.928571
          4.0       0.770833  0.937500
          5.0       0.791667  0.937500
          10.0      0.820000  0.920000

我想将这些数据绘制成两个不同的子图,一个用于所有 congruent == False 的值,另一个用于所有 congruent == True 的值。

我尝试执行x.plot(subplots=True),但这会为每个创建一个子图(即cresp1cresp2),这不是我想要的:

enter image description here

我怎样才能做我想做的事?

最佳答案

你可以自己画:

import pylab as pl
import io
import pandas as pd

txt = """congruent contrast  cresp1    cresp2
False     1.0       0.423077  0.442308
          2.0       0.537037  0.481481
          2.5       0.576923  0.634615
          3.0       0.568182  0.500000
          3.5       0.675000  0.750000
          4.0       0.687500  0.604167
          5.0       0.687500  0.875000
          10.0      0.869565  0.913043
True      1.0       0.568182  0.386364
          2.0       0.547619  0.500000
          2.5       0.522727  0.477273
          3.0       0.557692  0.634615
          3.5       0.571429  0.928571
          4.0       0.770833  0.937500
          5.0       0.791667  0.937500
          10.0      0.820000  0.920000"""

df = pd.read_csv(io.BytesIO(txt), delim_whitespace=True).ffill()
df = df.set_index(["congruent","contrast"])
levels = df.index.levels[0]
fig, axes = pl.subplots(len(levels))

for level, ax in zip(levels, axes):
    df.loc[level].plot(ax=ax, title=str(level))

输出:

enter image description here

关于python - 如何选择哪个多索引轴将 groupby 对象中的数据拆分到不同的子图中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20059912/

相关文章:

python - 在python中排序单词

python - 使用分组边界的 SciPy 优化

python matplotlib 在axes.lines上迭代得到错误的长度

python - 为什么类别列被视为 pandas 中的字符串列?

python - 发现类型错误 : sequence item 3: expected string, float

python - 没有名为 azure.cosmos.cosmos_client 的模块

python - Matplotlib,图例符号之间的垂直空间

python - 比较具有不同 x 轴值的直方图

python - 根据列对某些行赋予权重

python - Pandas:如何删除 Pandas 数据框中所有列的前导缺失值?