我正在使用一个 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)
,但这会为每个列创建一个子图(即cresp1
与cresp2
),这不是我想要的:
我怎样才能做我想做的事?
最佳答案
你可以自己画:
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))
输出:
关于python - 如何选择哪个多索引轴将 groupby 对象中的数据拆分到不同的子图中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20059912/