countplot
📂

countplot

Codes

sns.countplot()

Notes

Visualizes the count of observations in each category.

Status
Done

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 the hue variable.
  • orient: Vertical ('v') or horizontal ('h') orientation. Automatically inferred if x or y 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: If True, separates bars by hue. 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 Focusdata 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()


image

Horizontal Orientation

Scenario: Visualizing the counts with horizontal bars.

Key Focusdata 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()
image

2. Count Plot with hue

Key Focushue.

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()
image

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 Focusorder.

image

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 Focushue_order.

image

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 Focusorient.

image
image

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 Focuspalette.

image

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 Focuscolor.

image

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 Focussaturation.

image

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 Focuswidth.

image

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 Focusdodge.

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

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 Focusax.

image