6

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 

2 Answers 2

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

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

2

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

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.