'Seaborn countplot generated in for-loop as subplots coming only visible in the last column
I have been searching across all questions and on-line platforms about how to visualize seaborn countplot as subplots in a for-loop.
I have created a list of the desired categorical column names from my database that I want to plot. The below code runs the loop but I am getting 4 rows with three empty columns and only in the last column the countplot (I assume the 4 rows are generated based on the number of the countplots). I have spent hours just trying to figure out how to do it but I can just get it right.
I would appreciate someone can just explain me what needs to be done to get the right display of the countplots as subplots(1,4).
##Code
categorical1= [ 'Gender', 'Customer Type', 'Type of Travel', 'Class']
##Forloop
for f in categorical1:
fig,axs= plt.subplots (1,4, figsize=(15,5))
sns.countplot(data= airline_customer_satisfactionc, x= airline_customer_satisfactionc[f], hue='satisfaction')
plt.show()
Thanks in advance for the patience with this python newbie.
Solution 1:[1]
Calling plt.subplots creates the figure and all of the subplots. That is why you are seeing four rows of four plots rather than one row of four plots. So you need to move that outside the for loop.
Then you need to tell seaborn which subplot it should draw the plot on, by passing the axes to its ax= parameter.
Finally, while this isn't a problem in your code, if you pass your dataframe to seaborn's data parameter, you can just pass the column name to x:
tips = sns.load_dataset("tips")
cols = ["day", "size", "sex", "smoker"]
f, axs = plt.subplots(1, len(cols), figsize=(10, 4))
for ax, col in zip(axs, cols):
sns.countplot(data=tips, x=col, hue="time", ax=ax)
f.tight_layout()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mwaskom |

