1

the task is to plot the top 5 NBA players according to accumulated points, as a bar plot, and to compare between east and west players

i implemented the solution in matplotlib but i want to know how to do it with FacetGrid


import numpy as np
import matploltlib.pyplot as plt
import pandas as pd

fake_data = {}
for i in range(100):
    name = str(float(np.random.rand(1)))
    pos = 'C' if np.random.rand(1) > 0.3 else 'D'
    pts = float(np.random.randint(0,2000,1))
    conf = 'East' if np.random.rand(1) > 0.5 else 'West'
    fake_data[name] = {'pos':pos,'pts':pts,'conf':conf}
fake_data = pd.DataFrame(fake_data).T
fake_data

df = fake_data
df_pos_c_east = df[(df['pos'] == 'C') & (df['conf'] == 'East')].sort_values('pts',ascending=False)[:5]
df_pos_c_east_pts = df_pos_c_east['pts']
df_pos_c_west = df[(df['pos'] == 'C') & (df['conf'] == 'West')].sort_values('pts',ascending=False)[:5]
df_pos_c_west_pts = df_pos_c_west['pts']
fig,axs = plt.subplots(1,2,figsize=[6,6])
df_pos_c_east_pts.plot.bar(ax=axs[0])
df_pos_c_west_pts.plot.bar(ax=axs[1])
fig.suptitle('Top scorers of position C by conf')
axs[0].title.set_text('East')
axs[1].title.set_text('West')

this code creates fake data identical to the one i have, and creates the figure i want using matplotlib. how do i create something similar with FacetGrid

any help would be appreciated!

enter_thevoid
  • 113
  • 1
  • 11

1 Answers1

0

I assume FacetGrid is seaborn's FacetGrid. If so, you can try extracting the data and plot like this:

plot_data = (df.sort_values('pts', ascending=False).groupby('pos').head(5)
               .assign(rank=lambda x: x.groupby('pos').cumcount())
            )

g = sns.FacetGrid(data=plot_data, col='conf', row='pos' )
g.map(sns.barplot, 'rank','pts', order=range(5))

Output:

enter image description here

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74