ggplot2 to Plotnine: How to Translate R Plots to Python

Convert ggplot2 code to plotnine: quote column names, wrap the plot in parentheses, rename dotted theme arguments, and watch for the differences that raise errors.

Most ggplot2 code works in plotnine after a few syntax changes: put column names in quotes, wrap the expression in parentheses, write True, False, and None, and replace dots in theme arguments with underscores. The examples use plotnine 0.15 and its bundled copy of ggplot2's mpg dataset.

Quick Example

Here is a plot in R:

library(ggplot2)

ggplot(mpg, aes(x = displ, y = hwy, color = drv)) +
  geom_point(alpha = 0.7) +
  geom_smooth(method = "lm", se = FALSE) +
  labs(title = "Bigger engines, fewer miles per gallon",
       x = "Engine size (L)", y = "Highway MPG", color = "Drive") +
  theme_bw() +
  theme(legend.position = "bottom")

The same plot in Python:

from plotnine import (aes, geom_point, geom_smooth, ggplot, labs, theme,
                      theme_bw)
from plotnine.data import mpg

scatter = (
    ggplot(mpg, aes(x="displ", y="hwy", color="drv"))
    + geom_point(alpha=0.7)
    + geom_smooth(method="lm", se=False)
    + labs(title="Bigger engines, fewer miles per gallon",
           x="Engine size (L)", y="Highway MPG", color="Drive")
    + theme_bw()
    + theme(legend_position="bottom")
)
scatter

Plotnine scatter plot of engine size against highway miles per gallon with a fitted line for each of the three drive types

ggplot2 to Plotnine Cheat Sheet

ggplot2 (R) plotnine (Python)
library(ggplot2) from plotnine import ggplot, aes, geom_point
aes(x = displ) aes(x="displ")
aes(factor(cyl)) aes("factor(cyl)")
TRUE, FALSE, NULL True, False, None
c(1, 2, 3) [1, 2, 3]
c("4" = "red", "f" = "blue") {"4": "red", "f": "blue"}
theme(axis.text.x = ...) theme(axis_text_x=...)
margin(b = 10) margin(b=10) from plotnine.themes.elements
facet_wrap(~ drv) facet_wrap("drv") or facet_wrap("~ drv")
facet_grid(year ~ drv) facet_grid("year ~ drv")
linewidth = 1 size=1
hjust, vjust in geom_text() ha, va
after_stat(count) after_stat("count")
stat_summary(fun = mean) stat_summary(fun_y=np.mean)
scale_fill_viridis_d() scale_fill_cmap_d("viridis")
scales::label_percent() label_percent() from mizani.labels
ggsave("plot.png", p) p.save("plot.png") or ggsave(p, "plot.png")
p1 \| p2 with patchwork p1 \| p2, built in since 0.15
print(p) p.show()

Write the Plot Across Several Lines

R continues a line that ends in +. Python doesn't, so wrap the whole plot in parentheses and put + at the start of each line, as above.

from plotnine import * lets you paste R code with fewer changes. In scripts and packages, import names explicitly so readers and linters know where each one comes from.

Column Names Are Strings

Everything inside aes() is a string that plotnine evaluates as Python. Expressions work, using Python functions you have imported:

import numpy as np
from plotnine import geom_boxplot

(ggplot(mpg, aes("np.log(displ)", "hwy / cty")) + geom_point())

One catch applies to this dataset: class is a reserved word in Python. A bare aes("class") works, but an expression such as "factor(class)" or "reorder(class, hwy)" raises PlotnineError with an "invalid syntax" message. Rename the column first.

reorder() Uses the Median by Default

R's reorder() sorts categories by their mean. Plotnine's uses the median, so the same code can give a different order. Pass fun=np.mean to match R.

ggplot(mpg, aes(reorder(class, hwy), hwy)) +
  geom_boxplot() +
  coord_flip()
from plotnine import coord_flip, theme_minimal

cars = mpg.rename(columns={"class": "vehicle_class"})

ordered = (
    ggplot(cars, aes("reorder(vehicle_class, hwy, fun=np.mean)", "hwy"))
    + geom_boxplot(fill="#bde0fe")
    + coord_flip()
    + labs(x="", y="Highway MPG")
    + theme_minimal()
)
ordered

Horizontal box plots of highway miles per gallon by vehicle class, ordered by mean from pickup at the bottom to compact at the top

In this data, midsize cars have a higher median than subcompacts (27 vs 26) but a lower mean, so the two swap places depending on fun.

Method Chains Replace dplyr Pipes

Prepare the data with pandas, then hand it to ggplot(). The >> operator pipes a DataFrame straight in, much like %>% or |>.

mpg %>%
  filter(year == 2008) %>%
  ggplot(aes(drv, fill = drv)) +
  geom_bar() +
  facet_wrap(~ cyl)
from plotnine import element_text, facet_wrap, geom_bar, scale_fill_cmap_d

piped = (
    mpg.query("year == 2008")
    >> ggplot(aes("drv", fill="drv"))
    + geom_bar(show_legend=False)
    + facet_wrap("cyl", nrow=1)
    + scale_fill_cmap_d("viridis")
    + labs(title="2008 models by drive type and cylinders", x="Drive", y="Cars")
    + theme_bw()
    + theme(strip_text=element_text(weight="bold"))
)
piped

Bar charts of 2008 car counts by drive type in four panels, one for each cylinder count, colored with the viridis palette

Which differences raise errors?

If you write You get Use instead
geom_line(linewidth=2) parameter not understood size=2
geom_text(hjust=0) parameter not understood ha="left"
theme(**{"axis.text.x": ...}) no themeable element axis_text_x
stat_summary(fun=np.mean) parameter not understood fun_y=np.mean
geom_smooth(method="loess") asks for scikit-misc pip install scikit-misc
aes(displ, hwy) NameError aes("displ", "hwy")
geom_bar() with only y mapped KeyError: 'x' aes("drv") plus coord_flip()

Which differences change the output without an error?

  • Text size. ggplot2 measures geom_text(size=...) in millimeters, and plotnine uses points (default 11). Multiply R values by about 2.85, so size = 4 becomes size=11.
  • Default smoother. For fewer than 1,000 points per group, geom_smooth() uses loess in both, but without scikit-misc plotnine falls back to lowess, which draws no confidence band. With larger groups, plotnine fits a GLM and ggplot2 a GAM.
  • Title alignment. Plotnine centers a title that has no subtitle. ggplot2 left-aligns it.
  • Category order. The reorder() default above.

What is missing from Plotnine?

Plotnine 0.15 has no coord_polar() (so no pie charts this way), no geom_sf(), and no secondary axes through sec_axis(). For maps, geom_map() draws GeoPandas data. For repelled labels, pass adjust_text to geom_text() with the adjustText package installed. Extension packages written in R, such as ggridges or ggrepel, don't carry over. For a pie or dual-axis chart, use Matplotlib.

Similar Topics