如何在Python中使用groupby为多个组的平均值添加折线图

时间:2020-04-11 21:28:05

标签: python pandas dataframe matplotlib

我有下面的代码,堆栈溢出的成员帮助我放在一起像一个csv,并为多行使用for循环(按一列中的某个值分组)。

Example Data Table

我正在尝试在每个分组值及其图上绘制均值。我对如何在每个组的多个列上实际创建均值感到困惑。在此方面以及如何调整代码方面的帮助将不胜感激!

期望的结果在这里The desired outcome figure.

我的代码在这里

import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

#read CSV
df=pd.read_csv('/Users/fabienlaugier/Documents/GeoComp/Data/Profiles.csv')

#Make Variables from dataframe columns
Value = df['Value']
Xposition = df['Xposition']
SectionName = df['Profile']

#Set up figure that will plot multiple line plots over each Group
fig, ax = plt.subplots()

for Profile, group in df.groupby('SectionName'):
    group.plot(x='Xposition', y='Value', ax=ax, label=Profile, c='grey')
ax.set_title('SectionName')
ax.set_xlabel("Xposition")
ax.set_ylabel("Value")

plt.show()

1 个答案:

答案 0 :(得分:1)

这是我使用pivot的方法:

s = df.pivot('Xposition', 'SectionName','Value')
# in case of duplicated data:
# s = df.pivot_table(index='Xposition', columns='SectionName', values='Value', aggfunc='mean')

ax = s.plot(color='gray')
s.mean(1).plot(ax=ax, color='b', linestyle='--', label='Mean')
ax.legend()

输出:

enter image description here

注意:如果您删除color='gray'中的s.plot,则会得到:

enter image description here