python - How to add a line plot plot for the average value across multiple groups using groupby in Python
问题描述
I have the code (below) that members of stack overflow have helped me put together to take a csv like and use a for loop for multiple lines (grouped by a certain value in one of the columns).
I'm trying to plot the mean across each of those grouped values and their plots. I'm realizing im confused on how to actually create a mean across multiple columns for each group. Help on this and how to adjust the code would be more than appreciated!
the code I have is here
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()
解决方案
This is my approach with 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()
Output:
Note: if you remove color='gray'
in s.plot
, you get:
推荐阅读
- javascript - webpack如何压缩HTML代码中的链接CSS文件?
- python - 在 python bokeh 中,如何在没有 js 的情况下以交互方式修改 fill_color 的字段?
- mdriven - MDrivenServer - 如何将视图模型公开为 REST 服务
- c# - WPF - DataGrid 不显示列表
- asp.net-core - 使用 Moq 的 ASP.NET Core 集成测试和模拟
- excel - 有没有办法从 powerpoint 演示文稿中创建 excel 工作表?
- facebook - 如何在本机反应中显示 facebook 用户名?
- go - 如何使用 go-git 查找原始/主的 sha?
- android - 拖动时 ImageView 无法正确移动
- ruby - 带有 DocuSign_eSign gem 的 SSO 身份验证流程:“未找到或禁用指定的集成商密钥。”