从 Excel 复制数据透视表,包含三个“行”(组)

问题描述 投票:0回答:1

我正在尝试在 python(pandas 或 matplotlib)中复制绘图,但似乎无法得到它。

数据看起来像 this - 我有多种类型的植物,用不同浓度的化合物处理,并且要么暴露于压力,要么不暴露于压力。

Excel 提供 this plot,它可以工作,但我无法在其上放置错误栏。我必须添加误差线(SEM)。

我用

data.groupby(['Plant', 'Concentration', 'Stress']).mean().unstack().plot.bar()
做了一些图,但它们不是很漂亮。大多数情况下,底部的分组不好。我也尝试过
pivot_table
,但结果是相似的。

python pandas matplotlib multi-index
1个回答
0
投票

使用seaborn(一个扩展matplotlib的库,用于统计可视化)。 Seaborn 自动创建误差线(默认情况下“ci”:平均值的 95% 置信区间,通过 bootstrapping 计算)。

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

N = 120
df = pd.DataFrame({'Plant': np.random.choice(['Pepper', 'Tomato'], N),
                   'Concentration': np.random.randint(0, 3, N),
                   'Parameter': np.random.randint(5, 25, N),
                   'Stress': np.random.choice(['Yes', 'No'], N), })
sns.set_style('whitegrid')
sns.catplot(df, kind='bar', x='Concentration', y='Parameter', hue='Stress', col='Plant')

plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.