Sorted Horizontal Bar Charts with Labels in Matplotlib

Make a horizontal bar chart with barh, sort it so the largest bar is on top, add value labels, and handle long names and negative values.

To make a horizontal bar chart in Matplotlib, call ax.barh(categories, values). barh draws the first item at the bottom, so sort your data in ascending order to put the largest bar on top, then pass the returned bars to ax.bar_label() to write each value.

Quick Example

import matplotlib.pyplot as plt
import pandas as pd

loans = pd.Series(
    {"Mystery": 4210, "Cooking": 1875, "Science fiction": 2960, "Biography": 2240,
     "Children's": 6480, "Travel": 990, "History": 2515, "Poetry": 430}
).sort_values()

fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
bars = ax.barh(loans.index, loans.values, color="#0f766e")
ax.bar_label(bars, fmt="{:,.0f}", padding=4)
ax.set_title("Library loans by genre, last quarter", loc="left")
ax.spines[["top", "right", "bottom"]].set_visible(False)
ax.set_xticks([])
ax.margins(x=0.1)
plt.show()

Sorted horizontal bar chart of library loans by genre with value labels, from Children's at 6,480 down to Poetry at 430

Children's books account for close to 30% of the 21,700 loans. With every bar labeled, the x-axis ticks repeat the same information, so the example removes them. The code targets Matplotlib 3.10 and 3.11.

How Do I Sort a Horizontal Bar Chart?

Matplotlib plots categories in the order you pass them, starting at the bottom. You have two choices:

  • Rank by value: sort ascending before plotting (series.sort_values() or df.sort_values("column")).
  • Keep your list order, read top to bottom: call ax.invert_yaxis(). This suits categories with a natural order, such as survey answers or age bands.
fruit = ["Apples", "Bananas", "Cherries", "Dates"]
crates = [34, 51, 12, 23]

fig, axes = plt.subplots(1, 3, figsize=(11, 2.8), layout="constrained")
axes[0].barh(fruit, crates, color="#a16207")
axes[0].set_title("Default: first item at the bottom")
axes[1].barh(fruit, crates, color="#a16207")
axes[1].invert_yaxis()
axes[1].set_title("invert_yaxis(): list order")
ordered = sorted(zip(crates, fruit))
axes[2].barh([f for _, f in ordered], [c for c, _ in ordered], color="#a16207")
axes[2].set_title("Sorted: largest on top")
plt.show()

Three horizontal bar charts of fruit crates showing the default bottom-up order, an inverted y-axis, and bars sorted with the largest on top

Without pandas, sorted(zip(values, names)) sorts the pairs together, as in the third panel.

Highlight One Bar and Keep "Other" Last

Catch-all categories read best at the end, whatever their size. Sort on a boolean column first, then on the value. False sorts before True, so ascending=[False, True] places "Other" first in the data, which is the bottom of the chart.

bar_label also accepts a labels list, which lets you show a count and a share together.

import numpy as np

causes = pd.DataFrame({
    "cause": ["Weather", "Crew scheduling", "Other", "Late inbound aircraft",
              "Maintenance", "Air traffic control"],
    "delays": [318, 142, 205, 467, 189, 96],
})
causes["is_other"] = causes["cause"] == "Other"
causes = causes.sort_values(["is_other", "delays"], ascending=[False, True])
colors = np.where(causes["delays"] == causes.loc[~causes["is_other"], "delays"].max(),
                  "#dc2626", "#cbd5e1")
share = causes["delays"] / causes["delays"].sum()

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
bars = ax.barh(causes["cause"], causes["delays"], color=colors)
ax.bar_label(bars, labels=[f"{d}  ({s:.0%})" for d, s in zip(causes["delays"], share)], padding=4)
ax.set_title("Late inbound aircraft cause the most delays", loc="left")
ax.spines[["top", "right", "bottom"]].set_visible(False)
ax.set_xticks([])
ax.margins(x=0.18)
plt.show()

Horizontal bar chart of flight delay causes with late inbound aircraft highlighted in red at 467 delays or 33 percent and Other kept at the bottom

For more on conditional colors, see coloring Matplotlib bars by value.

Put Labels Inside the Bars

You can drop the axis entirely and write the name and value inside each bar. Each bar's vertical center is bar.get_y() + bar.get_height() / 2. This uses ax.text because bar_label doesn't let you override ha.

services = ["Checkout", "Search", "Login", "Recommendations", "Image resize"]
latency = np.array([480, 365, 290, 210, 160])

fig, ax = plt.subplots(figsize=(8, 3.8), layout="constrained")
bars = ax.barh(services, latency, height=0.75, color="#4338ca")
for bar, name, value in zip(bars, services, latency):
    middle = bar.get_y() + bar.get_height() / 2
    ax.text(8, middle, name, va="center", color="white")
    ax.text(value - 8, middle, f"{value} ms", va="center", ha="right",
            color="white", fontweight="bold")
ax.invert_yaxis()
ax.set_axis_off()
ax.set_title("95th percentile latency by service", loc="left")
plt.show()

Horizontal bar chart of service latency with white service names on the left and millisecond values on the right inside each indigo bar

This only works when the shortest bar has room for both pieces of text. Check it again if the data changes.

Wrap Long Category Names

Long names are the usual reason to switch from vertical to horizontal bars. textwrap.fill(text, width=28) from the standard library breaks them onto several lines, with no need to rotate the axis labels.

import textwrap

answers = [
    "I could not find the setting I was looking for",
    "The price was higher than I expected",
    "I only wanted to compare options before deciding later",
    "My preferred payment method was not available",
]
votes = [41, 67, 88, 23]
order = np.argsort(votes)
wrapped = [textwrap.fill(answers[i], width=28) for i in order]

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
bars = ax.barh(wrapped, np.array(votes)[order], color="#be185d")
ax.bar_label(bars, padding=3)
ax.set_title("Why did you leave without ordering?", loc="left")
ax.spines[["top", "right"]].set_visible(False)
ax.set_xlabel("Survey responses")
plt.show()

Sorted horizontal bar chart of survey answers with long category names wrapped onto two or three lines

Plot Positive and Negative Values

bar_label places labels past the end of each bar, to the left for negative values. The {:+.1f}% format keeps the plus sign on gains, and ax.axvline(0) marks the baseline.

change = pd.Series(
    {"North": 8.4, "Coast": -3.1, "Central": 2.2, "Valley": -7.6,
     "Hills": 5.0, "Islands": -1.4, "South": 11.3}
).sort_values()

fig, ax = plt.subplots(figsize=(8, 4.2), layout="constrained")
bars = ax.barh(change.index, change.values,
               color=["#b91c1c" if v < 0 else "#15803d" for v in change])
ax.bar_label(bars, fmt="{:+.1f}%", padding=3)
ax.axvline(0, color="black", linewidth=1)
ax.margins(x=0.14)
ax.set_title("Change in ridership by region, year over year", loc="left")
ax.spines[["top", "right", "left"]].set_visible(False)
ax.tick_params(axis="y", length=0)
ax.set_xlabel("Percent change")
plt.show()

Diverging horizontal bar chart of ridership change by region with green gains to the right of zero and red declines to the left

Grouped Horizontal Bars

For two series, place the bars at numeric positions, offset each series by half a bar height, and set the category names with ax.set_yticks(y, teams).

teams = ["Design", "Support", "Sales", "Engineering"]
planned = np.array([12, 30, 24, 41])
actual = np.array([15, 26, 29, 38])
y = np.arange(len(teams))
h = 0.38

fig, ax = plt.subplots(figsize=(8, 4.2), layout="constrained")
for offset, values, name, color in [(-h / 2, planned, "Planned", "#94a3b8"),
                                    (h / 2, actual, "Actual", "#ea580c")]:
    bars = ax.barh(y + offset, values, h, label=name, color=color)
    ax.bar_label(bars, padding=3, fontsize=9)
ax.set_yticks(y, teams)
ax.invert_yaxis()
ax.margins(x=0.08)
ax.set_title("Planned vs actual headcount", loc="left")
ax.legend(loc="upper right")
ax.spines[["top", "right"]].set_visible(False)
plt.show()

Grouped horizontal bar chart comparing planned and actual headcount for four teams

The same offset approach for vertical bars is covered in grouped bar charts with labels. To stack the series instead, see stacked bar charts with labels, swapping bar for barh and bottom for left.

barh or bar?

Situation Use
Long category names, or more than about 7 categories barh
Ranking from largest to smallest barh, sorted
Time periods such as months or years bar, so time runs left to right
A few short categories Either

The main argument names differ: barh(y, width, height=0.8, left=None) mirrors bar(x, height, width=0.8, bottom=None). From pandas, series.sort_values().plot.barh() draws the same chart on a Matplotlib Axes.

Similar Topics