0

I'm learning Python, specifically Pandas and Matplotlib at the moment. I have a dataset of Premier League Hattrick scorers and have been using pandas to do some basic analysis. I then want to produce a bar chart based on this data extract. I have been able to create a bar chart, but the X axis shows 'nan' instead of the player names.

My code to extract the data...

import matplotlib.pyplot as plt
import pandas as pd

top10 = df.groupby(['Player'])[['Goals']].count().sort_values(['Goals'],ascending=False).head(10)

This produces the following, which I know is a Pandas DataFrame as if I print the type of 'top10' i get the following:

<class 'pandas.core.frame.DataFrame'>

This produces the following if printed out...

DataFrame

I tried to create a chart direct from this dataFrame, but was given an error message 'KeyError: Player'

So, I made an new dataframe and plotted this, which was kind of successful, but it displayed 'nan' on the X access?

top10df = pd.DataFrame(top10,columns=['Player','Goals'])
top10df.plot(x ='Player', y='Goals', kind='bar')
plt.show()

Barchart

I did manually create a dataframe and it worked, so unsure where to go, tried googling and searching stackoverflow with no success. Any ideas please??

Neil White
  • 111
  • 4
  • 18
  • 1
    There is no `Player` column, that is the index. Therefore, remove `x ='Player',`: `top10df.plot(kind='bar')`. The index is automatically plotting as the axis, and the one column will also be plotted. – Trenton McKinney Nov 19 '21 at 14:00

1 Answers1

1

You could plot directly using the groupby results in the following way:

top10.plot(kind='bar', title='Your Title', ylabel='Goals',
         xlabel='Player', figsize=(6, 5))

A dummy example, since you did not supply your data (next time it's best to do so):

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'category': list('XYZXY'),
                   'sex': list('mfmff'),
                   'ThisColumnIsNotUsed': range(5,10)})
x = df.groupby('sex').count()
x.plot(kind='bar', ylabel='category', xlabel='sex')

we get:

enter image description here

David
  • 8,113
  • 2
  • 17
  • 36