Chopin
Chopin

Reputation: 214

Plot mean in subplots - Seaborn

I'm aiming to plot the mean for a group of subplots. Using below, I'm separating each unique Item into a separate subplots. I'm hoping to plot the relevant mean of Num to each of these subplots.

import pandas as pd
import seaborn as sns

df = pd.DataFrame({      
    'Num' : [1,2,1,2,3,2,1,3,2,2,1,2,3,3,1,3],
    'Label' : ['A','B','C','B','B','C','C','B','B','A','C','A','B','A','C','A'],  
    'Item' : ['Up','Left','Up','Left','Down','Right','Up','Down','Right','Down','Right','Up','Up','Right','Down','Left'],        
   })

g = sns.displot(data = df, 
               x = 'Num', 
               row = 'Item', 
               row_order = ['Up','Down','Left','Right'],
               discrete = True,
               aspect = 4, 
               height = 2,
               )

#for x in df['IMMEDIATE_CONGESTION_PLAYER_COUNT']:

plt.axvline(np.median(df['Num']),color='b', linestyle='--')

Upvotes: 0

Views: 444

Answers (1)

r-beginners
r-beginners

Reputation: 35115

Here is a great answer. For the initial graph object, use the map function to add a vertical line.

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({      
    'Num' : [1,2,1,2,3,2,1,3,2,2,1,2,3,3,1,3],
    'Label' : ['A','B','C','B','B','C','C','B','B','A','C','A','B','A','C','A'],  
    'Item' : ['Up','Left','Up','Left','Down','Right','Up','Down','Right','Down','Right','Up','Up','Right','Down','Left'],        
   })

g = sns.displot(data = df, 
               x = 'Num', 
               row = 'Item', 
               row_order = ['Up','Down','Left','Right'],
               discrete = True,
               aspect = 4, 
               height = 2,
               )

cols = df['Item'].unique()
for c,ax in zip(cols, g.axes.flat):
    ax.axvline(np.median(df[df['Item'] == c]['Num']), color='r', linestyle='--')

plt.show()

enter image description here

Upvotes: 1

Related Questions