I am trying to compare two players by showing a line graph of their points over the years. I want a line for each player, on the x-axis the Year, and on the y-axis the average Pts for that year. I can use a groupby to get the numbers but can't plot them separately on a graph.
Name Year Pts
2264 Mike Evans 2017 10.7
2266 T.Y. Hilton 2017 10.0
2440 Mike Evans 2013 7.5
10271 T.Y. Hilton 2013 12.4
10499 T.Y. Hilton 2013 1.3
Using pivot_table
with aggfunc='mean'
:
df.pivot_table('Pts', 'Year', 'Name', aggfunc='mean').plot(
kind='line', marker='o', xticks=df.Year.unique()
)
# Pivot table produces:
# Name MikeEvans T.Y.Hilton
# Year
# 2013 7.5 6.85
# 2017 10.7 10.00
seaborn
is a very useful library for plotting DataFrames
. For most plots, it allows you to specify a hue
parameter that essentially groups your data for plotting.
import seaborn as sns
sns.pointplot(data = df.groupby(['Name', 'Year']).mean().reset_index(),
x='Year', y='Pts', hue='Name')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With