Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line plot with multiple lines pandas

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 
like image 286
Zakary Krumlinde Avatar asked Aug 02 '18 02:08

Zakary Krumlinde


2 Answers

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

like image 111
user3483203 Avatar answered Sep 21 '22 04:09

user3483203


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

like image 30
ALollz Avatar answered Sep 20 '22 04:09

ALollz