33

I am trying to plot two countplots showing the counts of batting and bowling. I tried the following code:

l=['batting_team','bowling_team']
for i in l:
    sns.countplot(high_scores[i])
    mlt.show()

But by using this , I am getting two plots one below the other. How can i make them order side by side?

user517696
  • 2,102
  • 6
  • 22
  • 32

2 Answers2

74

Something like this:

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

batData = ['a','b','c','a','c']
bowlData = ['b','a','d','d','a']

df=pd.DataFrame()
df['batting']=batData
df['bowling']=bowlData


fig, ax =plt.subplots(1,2)
sns.countplot(df['batting'], ax=ax[0])
sns.countplot(df['bowling'], ax=ax[1])
fig.show()

enter image description here

The idea is to specify the subplots in the figure - there are numerous ways to do this but the above will work fine.

Robbie
  • 3,992
  • 1
  • 17
  • 23
  • Take a look for a more general solution without seaborn: https://stackoverflow.com/a/54266570/5084355 – Roman Orac Jan 19 '19 at 11:27
  • Why do I get 4 images? Two images are just empty and other two has the charts I wanted. – Ozkan Serttas Jan 25 '19 at 04:18
  • @cyber-math the code only generates two subplots, maybe you have entered something like: plt.subplots(2,2)? Have you tried to run this exact script? – Robbie Jan 25 '19 at 04:27
  • 1
    Thank you for the reply. Here is what I did `fig, ax =plt.subplots(1,2) sns.catplot(x='CDR',y='Age',data=long_df, ax=ax[0]) sns.catplot(x='CDR',y='MMSE',data=long_df, ax=ax[1])` removed `sharey` – Ozkan Serttas Jan 25 '19 at 04:28
  • I had this extra empty plot issue before and `plt.close()` worked that time. Now it is not working. – Ozkan Serttas Jan 25 '19 at 04:31
  • I'm not sure why that wouldn't work for you. It would probably be easier to open a new question and I'll try to help you out. Just comment here with the link when you have done that. – Robbie Jan 25 '19 at 04:34
3
import matplotlib.pyplot as plt
l=['batting_team', 'bowling_team']
figure, axes = plt.subplots(1, 2)
index = 0
for axis in axes:
  sns.countplot(high_scores[index])
  index = index+1
plt.show()
Pratik Kulkarni
  • 333
  • 3
  • 6
Ravi
  • 2,374
  • 1
  • 15
  • 31