sns.countplot()
Visualizes the count of observations in each category.
1. Count Plot: sns.countplot()
The sns.countplot()
function in Seaborn is a powerful tool for visualizing the frequency distribution of a categorical variable. It creates a bar plot where the height of each bar represents the count of occurrences for each unique category.
Syntax
sns.countplot(
data=None,
*,
x=None,
y=None,
hue=None,
order=None,
hue_order=None,
orient=None,
color=None,
palette=None,
saturation=0.75,
width=0.8,
dodge=True,
ax=None,
**kwargs,
)
Key Parameters
data
: The dataset (Pandas DataFrame or array-like) to visualize.x
: The categorical variable to be plotted on the x-axis.y
: The categorical variable to be plotted on the y-axis (used for vertical orientation).hue
: Another categorical variable to differentiate colors for subgroups within bars.order
: Specifies the order of categories to plot along the axis.hue_order
: Specifies the order of categories for thehue
variable.orient
: Vertical ('v') or horizontal ('h') orientation. Automatically inferred ifx
ory
is provided.palette
: Specifies the color palette for the plot.color
: Single color for all bars.saturation
: Adjusts the intensity of the colors.width
: Width of the bars.dodge
: IfTrue
, separates bars byhue
. Otherwise, bars are overlaid.ax
: Matplotlib axes to draw the plot onto.
Examples
Basic Count Plot
Scenario: Visualizing the distribution of a single categorical variable.
Key Focus: data
and x
.
import seaborn as sns
import matplotlib.pyplot as plt
# Sample Data
data = {'Category': ['A', 'B', 'A', 'C', 'A', 'B', 'C', 'B']}
df = pd.DataFrame(data)
# Count Plot
sns.countplot(data=df, x='Category')
plt.show()

Horizontal Orientation
Scenario: Visualizing the counts with horizontal bars.
Key Focus: data
and y
import seaborn as sns
import matplotlib.pyplot as plt
# Sample Data
data = {'Category': ['A', 'B', 'A', 'C', 'A', 'B', 'C', 'B']}
df = pd.DataFrame(data)
# Count Plot
sns.countplot(data=df, y='Category')
plt.show()

2. Count Plot with hue
Key Focus: hue
.
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Sample Data
data = {
'Category': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
'SubCategory': ['X', 'Y', 'X', 'Y', 'Y', 'X', 'X', 'Y', 'Y']
}
df = pd.DataFrame(data)
# Count Plot with hue
sns.countplot(data=df, x='Category', hue='SubCategory')
plt.title("Count Plot with hue")
plt.xlabel("Category")
plt.ylabel("Count")
plt.legend(title="SubCategory")
plt.show()

4. Specifying order
for Categories
Scenario: Changing the order of categories displayed on the x-axis.
sns.countplot(data=df, x='Category', order=['C', 'B', 'A'])
plt.title("Ordered Count Plot")
plt.show()
Key Focus: order
.

5. Customizing hue_order
Scenario: Rearranging the order of the subcategories (hue groups).
sns.countplot(
data=df,
x='Category',
hue='SubCategory',
hue_order=['Y', 'X']
)
plt.title("Count Plot with Hue Order")
plt.legend(title="SubCategory")
plt.show()
Key Focus: hue_order
.

6. Adjusting orient
Scenario: Explicitly setting the orientation to vertical or horizontal.
sns.countplot(data=df, x='Category', orient='v') # Vertical
plt.title("Vertical Orientation")
plt.show()
sns.countplot(data=df, y='Category', orient='h') # Horizontal
plt.title("Horizontal Orientation")
plt.show()
Key Focus: orient
.


7. Customizing palette
Scenario: Using a custom color palette for bars.
sns.countplot(data=df, x='Category', palette='Spectral', hue='SubCategory')
plt.title("Count Plot with Custom Palette")
plt.show()
Key Focus: palette
.

8. Setting a Single color
Scenario: Using a single color for all bars.
sns.countplot(data=df, x='Category', color='red')
plt.title("Single Color Count Plot")
plt.show()
Key Focus: color
.

9. Adjusting saturation
Scenario: Modifying the intensity of colors in the plot.
sns.countplot(data=df, x='Category', palette='coolwarm', saturation=0.5)
plt.title("Count Plot with Low Saturation")
plt.show()
Key Focus: saturation
.

10. Modifying Bar width
Scenario: Adjusting the bar width to avoid overlap or create a thinner appearance.
sns.countplot(data=df, x='Category', width=0.2, hue='SubCategory')
plt.title("Count Plot with Thin Bars")
plt.show()
Key Focus: width
.

11. Controlling dodge
Behavior
Scenario: Overlaying bars instead of separating by hue.
sns.countplot(data=df, x='Category', hue='SubCategory', dodge=False)
plt.title("Count Plot with Overlaid Bars")
plt.legend(title="SubCategory")
plt.show()
Key Focus: dodge
.

sns.countplot(data=df, x='Category', hue='SubCategory', dodge=True)
plt.title("Count Plot with Overlaid Bars")
plt.legend(title="SubCategory")
plt.show()

12. Drawing on a Specific ax
Scenario: Adding the count plot to an existing Matplotlib figure.
plt.style.use('ggplot')
fig, ax = plt.subplots(figsize=(20, 6))
sns.countplot(data=df, x='Category', ax=ax, palette='coolwarm', hue='SubCategory')
ax.set_title("Count Plot on Specific Axes")
plt.show(
Key Focus: ax
.
