Seaborn countplot: Count and Plot Categories

Use sns.countplot to count rows per category: sort the bars, label them with counts or percentages, split them with hue, go horizontal, and show only the top categories.

sns.countplot(data=df, x="column") counts the rows in each category and draws one bar per category. Sort the bars with order=df["column"].value_counts().index, and print the numbers on them with ax.bar_label().

Quick Example

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

# Sample data: 640 support tickets
rng = np.random.default_rng(64)
n = 640
topics = ["Billing", "Login", "Bug report", "Shipping", "Refund",
          "Feature request", "Account change", "Other"]
tickets = pd.DataFrame({
    "topic": rng.choice(topics, n, p=[.23, .19, .16, .13, .11, .08, .06, .04]),
    "channel": rng.choice(["Email", "Chat", "Phone"], n, p=[.45, .38, .17]),
})

sns.set_theme(style="whitegrid")
order = tickets["topic"].value_counts().index

fig, ax = plt.subplots(figsize=(9, 4.8))
sns.countplot(data=tickets, y="topic", order=order, color="#4f46e5", ax=ax)
ax.bar_label(ax.containers[0], padding=4)
ax.set(title="Support tickets by topic", xlabel="Tickets", ylabel="")
ax.grid(False)
sns.despine(left=True, bottom=True)
ax.set_xticks([])
plt.show()

Horizontal Seaborn countplot of support tickets by topic, sorted from Billing at the top to Other at the bottom, with the count written beside each bar

Putting the categories on y gives long names room without rotating them. The code targets Seaborn 0.13.

Vertical or Horizontal

x= draws vertical bars and y= draws horizontal ones. Pass one of the two.

fig, ax = plt.subplots(figsize=(8, 4.2))
sns.countplot(data=tickets, x="channel", color="#0891b2", width=0.6, ax=ax)
ax.set(xlabel="", ylabel="Tickets")
plt.show()

Vertical countplot with three bars for Chat, Email, and Phone tickets

Order the Bars

Without order, string categories appear in the order they're first seen in the data. Pass a list to control it:

by_count = tickets["topic"].value_counts().index             # largest first
smallest_first = tickets["topic"].value_counts().index[::-1]
alphabetical = sorted(tickets["topic"].unique())
fixed = ["Email", "Phone", "Chat"]                           # your own order

A pandas ordered Categorical column is plotted in its category order, which is handy for sizes, months, or survey scales. See changing category order in Seaborn.

Show Percentages Instead of Counts

stat accepts "count" (the default), "percent", "proportion", or "probability". It was added in Seaborn 0.13.

fig, ax = plt.subplots(figsize=(9, 4.8))
sns.countplot(data=tickets, y="topic", order=order, stat="percent",
              color="#0d9488", ax=ax)
ax.bar_label(ax.containers[0], fmt="%.1f%%", padding=4)
ax.set(xlabel="Share of tickets (%)", ylabel="")
ax.margins(x=0.1)
plt.show()

Horizontal countplot showing each ticket topic as a percentage of all tickets, labeled to one decimal place

Label Bars with Both Count and Percent

Build the label strings yourself and pass them to labels=:

fig, ax = plt.subplots(figsize=(9, 4.8))
sns.countplot(data=tickets, y="topic", order=order, color="#64748b", ax=ax)
bars = ax.containers[0]
labels = [f"{v:.0f}  ({v / len(tickets):.0%})" for v in bars.datavalues]
ax.bar_label(bars, labels=labels, padding=4)
ax.set(xlabel="Tickets", ylabel="")
ax.margins(x=0.18)
plt.show()

Horizontal countplot with each bar labeled with its ticket count followed by its percentage in parentheses

margins leaves space so the longest label stays inside the axes. More options are in displaying values on Seaborn bar plots.

Split Bars by a Second Column with hue

channel_colors = {"Email": "#334155", "Chat": "#0ea5e9", "Phone": "#f59e0b"}

fig, ax = plt.subplots(figsize=(10, 4.6))
sns.countplot(data=tickets, x="topic", order=order[:5], hue="channel",
              palette=channel_colors, ax=ax)
for bars in ax.containers:
    ax.bar_label(bars, fontsize=9, padding=2)
ax.set(xlabel="", ylabel="Tickets")
plt.show()

Grouped countplot of the five most common ticket topics split into email, chat, and phone bars, each labeled with its count

Each hue level is its own container, so loop over ax.containers to label every bar.

Percent Within Each Group

With hue, stat="percent" is a share of all rows: the bars across the whole chart add up to 100. For the share within each topic, or a 100% stacked bar, use histplot:

fig, ax = plt.subplots(figsize=(9, 4.4))
sns.histplot(data=tickets, y=pd.Categorical(tickets["topic"], categories=order),
             hue="channel", hue_order=list(channel_colors), palette=channel_colors,
             multiple="fill", discrete=True, shrink=0.8, ax=ax)
ax.set(xlabel="Share of each topic's tickets", ylabel="")
sns.move_legend(ax, "lower center", bbox_to_anchor=(0.5, 1), ncol=3, title=None,
                reverse=True)  # match the left-to-right order of the segments
plt.show()

Horizontal 100 percent stacked bars showing the split of email, chat, and phone within each ticket topic

If you need the numbers too, pd.crosstab(tickets["topic"], tickets["channel"], normalize="index") returns them as a table.

Show Only the Top Categories

order also filters: categories left out of the list aren't drawn. To keep the remainder visible, combine it into one bar first.

top = tickets["topic"].value_counts().drop("Other").head(4).index
grouped = tickets["topic"].where(tickets["topic"].isin(top), "Everything else")

fig, ax = plt.subplots(figsize=(8, 3.8))
sns.countplot(y=grouped, order=[*top, "Everything else"], color="#be185d", ax=ax)
ax.bar_label(ax.containers[0], padding=4)
ax.set(xlabel="Tickets", ylabel="")
ax.margins(x=0.1)
plt.show()

Countplot of the four largest ticket topics followed by a bar combining all remaining topics

Color Each Bar Differently

Assign the category to hue as well, and turn off the repeated legend. Passing palette without hue is deprecated.

fig, ax = plt.subplots(figsize=(9, 4.6))
sns.countplot(data=tickets, y="topic", order=order, hue="topic",
              hue_order=order, palette="viridis", legend=False, ax=ax)
ax.set(xlabel="Tickets", ylabel="")
plt.show()

Horizontal countplot with a different viridis color for each ticket topic

To highlight one category, a mapping works well: palette={t: "#e11d48" if t == "Refund" else "#cbd5e1" for t in topics}.

countplot vs barplot

You have Use
One row per observation, and you want counts countplot
A value to average or sum per category barplot (with estimator=)
Counts already computed barplot, or ax.bar()
A numeric column to bin histplot
One count chart per subgroup catplot(kind="count")

Similar Topics