Plotnine Bar Charts with geom_bar and geom_col

Make bar charts in Plotnine: count rows with geom_bar, plot values with geom_col, then sort, label, group, and stack the bars.

Plotnine has two bar geoms. geom_col() draws bars from values already in your data, and geom_bar() counts the rows in each category for you. The examples use plotnine 0.15.

Quick Example

A sorted horizontal bar chart with a value on each bar.

import pandas as pd
from plotnine import (aes, coord_flip, geom_col, geom_text, ggplot, labs,
                      scale_y_continuous, theme_minimal)

drinks = pd.DataFrame({
    "drink": ["Latte", "Drip coffee", "Cold brew", "Cappuccino", "Tea", "Mocha"],
    "cups": [412, 365, 298, 187, 142, 96],
})

labeled = (
    ggplot(drinks, aes("reorder(drink, cups)", "cups"))
    + geom_col(fill="#7f5539", width=0.7)
    + geom_text(aes(label="cups"), ha="left", nudge_y=5, size=10)
    + coord_flip()
    + scale_y_continuous(expand=(0, 0, 0.1, 0))
    + labs(title="Cups sold last week", x="", y="Cups")
    + theme_minimal()
)
labeled

Horizontal Plotnine bar chart of cups sold, from Latte at 412 down to Mocha at 96, each bar labeled with its value

reorder(drink, cups) sorts the bars by value, coord_flip() turns them horizontal, and expand=(0, 0, 0.1, 0) starts the bars at the axis while leaving 10% of headroom for the labels.

What is the difference between geom_bar and geom_col?

geom_col() geom_bar()
Aesthetics x and y x only
Bar height the value in y number of rows in the category
Default stat "identity" "count"
Use it for totals, averages, summary tables raw data, one row per event

Passing y to geom_bar() raises PlotnineError: stat_count() must not be used with a y aesthetic. Switch to geom_col(), which is the same as geom_bar(stat="identity"). Unlike ggplot2, plotnine's geom_bar() also won't take y alone for horizontal bars, so map x and add coord_flip().

Count Rows with geom_bar

Here each row is one order. geom_bar() needs only the column to count. Making the column categorical with value_counts() order puts the biggest bar first.

import numpy as np
from plotnine import geom_bar

rng = np.random.default_rng(41)
orders = pd.DataFrame({
    "size": rng.choice(["Small", "Medium", "Large", "Extra large"], 500,
                       p=[0.22, 0.43, 0.27, 0.08]),
})
orders["size"] = pd.Categorical(orders["size"],
                                categories=orders["size"].value_counts().index)

counts = (
    ggplot(orders, aes("size"))
    + geom_bar(fill="#2a9d8f")
    + labs(title="Orders by cup size", x="", y="Orders")
    + theme_minimal()
)
counts

Plotnine bar chart counting orders by cup size, sorted from Medium to Extra large

Show Percentages Instead of Counts

after_stat() refers to values the stat computed, here count. Map it in y to get shares, and in a geom_text() with stat="count" to label them.

from mizani.labels import label_percent
from plotnine import after_stat

share = (
    ggplot(orders, aes("size"))
    + geom_bar(aes(y=after_stat("count / sum(count)")), fill="#e76f51")
    + geom_text(
        aes(y=after_stat("count / sum(count)"),
            label=after_stat("count / sum(count)")),
        stat="count", va="bottom", nudge_y=0.005, format_string="{:.0%}",
    )
    + scale_y_continuous(labels=label_percent(), expand=(0, 0, 0.1, 0))
    + labs(title="Share of orders by cup size", x="", y="Share of orders")
    + theme_minimal()
)
share

Plotnine bar chart of the share of orders for each cup size, with a percentage above each bar

How do I sort bars in Plotnine?

Plotnine draws string categories alphabetically. There are three ways to change that:

  • aes("reorder(drink, cups)", "cups") sorts ascending by cups. Add ascending=False inside reorder() to flip it.
  • pd.Categorical(..., categories=[...]) stores the order in the DataFrame, which suits natural orders such as sizes or weekdays.
  • scale_x_discrete(limits=["Tea", "Latte"]) sets the order on one chart and drops any category you leave out.

With several rows per category, reorder() sorts by the median of each group. Pass fun=np.sum to sort by totals. In a flipped chart, ascending order puts the largest bar on top.

Grouped Bar Chart

Map a second column to fill and place the bars side by side with position_dodge(). Give geom_text() the same dodge width as the bars so each label lands on its own bar.

from plotnine import position_dodge, scale_fill_manual, theme

sales = pd.DataFrame({
    "quarter": ["Q1", "Q2", "Q3", "Q4"] * 2,
    "shop": ["Downtown"] * 4 + ["Harbor"] * 4,
    "revenue": [48, 53, 61, 57, 31, 44, 66, 39],
})
dodge = position_dodge(width=0.8)

grouped = (
    ggplot(sales, aes("quarter", "revenue", fill="shop"))
    + geom_col(position=dodge, width=0.75)
    + geom_text(aes(label="revenue"), position=dodge, va="bottom",
                format_string="${}k", size=9)
    + scale_fill_manual(values={"Downtown": "#264653", "Harbor": "#f4a261"})
    + scale_y_continuous(expand=(0, 0, 0.1, 0))
    + labs(title="Revenue by shop", x="", y="Revenue ($ thousands)", fill="")
    + theme_minimal()
    + theme(legend_position="top")
)
grouped

Grouped Plotnine bar chart of quarterly revenue for the Downtown and Harbor shops, with Harbor ahead only in Q3

If a group is missing from one category, the remaining bar widens to fill the space. position_dodge(preserve="single") keeps all bars the same width.

Stacked Bar Chart

Stacking is the default when fill is mapped. To label each segment, use position_stack(vjust=0.5), which centers the text inside it.

from plotnine import position_stack

sales_colors = scale_fill_manual(values={"Downtown": "#264653", "Harbor": "#f4a261"})

stacked = (
    ggplot(sales, aes("quarter", "revenue", fill="shop"))
    + geom_col(width=0.7)
    + geom_text(aes(label="revenue"), position=position_stack(vjust=0.5),
                color="white", size=10)
    + sales_colors
    + scale_y_continuous(expand=(0, 0, 0.05, 0))
    + labs(title="Total revenue per quarter", x="",
           y="Revenue ($ thousands)", fill="")
    + theme_minimal()
    + theme(legend_position="top")
)
stacked

Stacked Plotnine bar chart of quarterly revenue split by shop, with Q3 the largest total at 127 thousand dollars

100% Stacked Bar Chart

position="fill" scales every bar to 1, so you compare proportions. Compute the percentages first if you want them as labels.

from plotnine import position_fill

sales["share"] = sales["revenue"] / sales.groupby("quarter")["revenue"].transform("sum")

percent = (
    ggplot(sales, aes("quarter", "revenue", fill="shop"))
    + geom_col(position="fill", width=0.7)
    + geom_text(aes(label="share"), position=position_fill(vjust=0.5),
                format_string="{:.0%}", color="white", size=10)
    + sales_colors
    + scale_y_continuous(labels=label_percent(), expand=(0, 0))
    + labs(title="Revenue mix per quarter", x="", y="Share of revenue", fill="")
    + theme_minimal()
    + theme(legend_position="top")
)
percent

100 percent stacked Plotnine bar chart where Harbor's share of revenue rises from 39 percent in Q1 to 52 percent in Q3

Practical Tips

  • fill colors the inside of a bar. color only changes its outline.
  • Set a constant color on the geom, geom_col(fill="#2a9d8f"). Putting it inside aes() treats the string as data.
  • Use horizontal bars when category names are long.
  • Start bar axes at zero. ylim(100, 500) removes every bar, because each one starts at 0, outside the limits.
  • To zoom without dropping data, use coord_cartesian(ylim=(...)), and prefer a dot plot if zero isn't meaningful.

Similar Topics