无法创建格式化的 pandas 多索引条形图?
Cannot create a formatted pandas multindex barplot?
我有一个多索引 pandas 数据框,如下所示:
cis-aconitate cis-aconitate +1 ... cis-aconitate +5 cis-aconitate +6
GROUP ...
mean ADE 1.481639 0.696184 ... 0.193380 0.018597
VEH 1.000000 1.000000 ... 1.000000 1.000000
std ADE 0.307211 0.209418 ... 0.114939 0.020461
VEH 0.573162 0.412895 ... 0.384928 0.752999
像这样建立索引:
MultiIndex([('mean', 'ADE'),
('mean', 'VEH'),
( 'std', 'ADE'),
( 'std', 'VEH')],
names=[None, 'GROUP'])
我正在尝试创建 y 轴上平均值的条形图。使用 df.unstack()
然后 df.plot.bar()
我可以得到这个:
但我最终想要的是只有方法,'cis-aconitate, cis-aconitate +1 ...' 横跨 x 轴,分为 ADE 和 VEH(每种颜色),然后 'std' 值用于误差条。这被证明是非常棘手的。谁能帮忙?提前致谢!
为避免对数据框进行大量转换,并基于this example, the solution I found was to split the means from the errors using cross section。
import pandas as pd
# Example data
index = pd.MultiIndex.from_tuples([('mean', 'ADE'), ('mean', 'VEH'), ( 'std', 'ADE'), ('std', 'VEH')], names=[None, 'GROUP'])
df = pd.DataFrame({'cis-aconitate': [1.5, 1, 0.3, 0.2], 'cis-aconitate +1': [0.7, 1, 0.2, 0.4]}, index=index)
df
# Split dataframe into means and errors
means = df.xs('mean').transpose()
errors = df.xs('std').transpose()
means.plot.bar(yerr=errors)
我有一个多索引 pandas 数据框,如下所示:
cis-aconitate cis-aconitate +1 ... cis-aconitate +5 cis-aconitate +6
GROUP ...
mean ADE 1.481639 0.696184 ... 0.193380 0.018597
VEH 1.000000 1.000000 ... 1.000000 1.000000
std ADE 0.307211 0.209418 ... 0.114939 0.020461
VEH 0.573162 0.412895 ... 0.384928 0.752999
像这样建立索引:
MultiIndex([('mean', 'ADE'),
('mean', 'VEH'),
( 'std', 'ADE'),
( 'std', 'VEH')],
names=[None, 'GROUP'])
我正在尝试创建 y 轴上平均值的条形图。使用 df.unstack()
然后 df.plot.bar()
我可以得到这个:
为避免对数据框进行大量转换,并基于this example, the solution I found was to split the means from the errors using cross section。
import pandas as pd
# Example data
index = pd.MultiIndex.from_tuples([('mean', 'ADE'), ('mean', 'VEH'), ( 'std', 'ADE'), ('std', 'VEH')], names=[None, 'GROUP'])
df = pd.DataFrame({'cis-aconitate': [1.5, 1, 0.3, 0.2], 'cis-aconitate +1': [0.7, 1, 0.2, 0.4]}, index=index)
df
# Split dataframe into means and errors
means = df.xs('mean').transpose()
errors = df.xs('std').transpose()
means.plot.bar(yerr=errors)