Let’s check how to make a countplot in Seaborn. I’ll load taxis built-in data to show you the countplot in detail.
The full seaborn.countplot consist of several parameters:
(*, x=None, y=None, hue=None, data=None,
order=None, hue_order=None, orient=None,
color=None, palette=None, saturation=0.75,
dodge=True, ax=None, **kwargs)
I will share my knowledge to explain to you you parameters of the countplot Seaborn method. It will help you to create a move advanced Seaborn countplot.
This is the completed code to create a counterplot in Python using the Seaborn module.
import seaborn as sns import matplotlib.pyplot as plt df = sns.load_dataset('taxis') sns.countplot(x='passengers', data=df) plt.show()
Countplot ratation
To flip the chart, just change the x argument to y.
sns.countplot(y='passengers', data=df)
You can also use a orient parameter and set “v” for a vertical alignment or “h” for a horizontal one.
Countplot hue
To increase the amount of data in the chart you may use the hue parameter. It is adding an additional sets of data to your counterplot graph. I decided to visualize payments with color of the taxi to check the relationship between them.
sns.countplot(x='payment', data=df, hue='color')
Countplot hue_order
The hue_order parameter gives you the possibility of changing the order of a hue. I used simply df[‘color’].value_counts().index[::-1] structure to change the order by index in the reverse order.
sns.countplot(x='payment', data=df, hue='color', hue_order = df['color'].value_counts().index[::-1])
Countplot order
To sort the data series use the order parameter. I picked df[‘passengers’].value_counts().index to sort counts.
sns.countplot(x='passengers', data=df, order=df['passengers'].value_counts().index)
Countplot ascending order
To sort the data series in ascending order, add the reverse indexing using index[::-1].
sns.countplot(x='passengers', data=df, order=df['passengers'].value_counts().index[::-1])
Countplot color
It is also possible to change the color of your python countplot. I set the color parameter to blue.
sns.countplot(x='passengers', data=df, color='blue')
Countplot palette
If one color is not enough for you or you want to make your chart look more attractive, use the palette parameter. I dediced to use the inferno.
sns.countplot(x='passengers', data=df, palette='inferno')
Countplot saturation
For those who care about details, you can also change the color saturation. The default is 0.75. Watch the saturation change as you lower it to 0.2.
sns.countplot(x='passengers', data=df, saturation=0.2)
Countplot dodge
To stack data in a countplot, use a dodge. By default, dodge is set to true. If you change this parameter to false, the count graph will change like this. The data has been accumulated.
sns.countplot(x='payment', data=df, hue='color', dodge=False)
These are all the parameters of the countplot method that I wanted to discuss for you. I hope you will improve your charting skills at Seaborn with this python course.