首页 > 解决方案 > 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).

Example Data Table

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 desired outcome is here The desired outcome figure.

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()

标签: pythonpandasdataframematplotlib

解决方案


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:

enter image description here

Note: if you remove color='gray' in s.plot, you get:

enter image description here


推荐阅读