# Packages
import geopandas as gp
import pandas as pd
import plotnine as pn
import textwrap
# Load data
ratios = pd.read_csv('data/affordability.csv')
gdf = gp.read_file("data/lad.geojson")
gdf = gdf[gdf["LAD25CD"].str.startswith(("E", "W"))]
gdf = gdf.to_crs("EPSG:27700")
# Join data
gdf = gdf.merge(
ratios,
how="left",
left_on="LAD25CD",
right_on="Local authority code"
)
# Fix data type
gdf["2025"] = pd.to_numeric(gdf["2025"], errors="coerce")
# Text
title_text = "The number of local authority areas with an affordability ratio above 12 has more than halved since 2021"
wrapped_title = '\n'.join(textwrap.wrap(title_text, width=55))
st_text = "Housing affordability ratio by local authority district, England and Wales, 2025"
wrapped_subtitle = '\n'.join(textwrap.wrap(st_text, width=70))
cap_text = "Housing affordability ratio, earnings, and house sales prices by local authority district, England and Wales, 1997 to 2025"
wrapped_cap = '\n'.join(textwrap.wrap(cap_text, width=80))
# Map
p = (
pn.ggplot()
+ pn.geom_map(data=gdf, mapping=pn.aes(fill="2025"), color="#f4f4f4", size=0.1)
+ pn.scale_fill_cmap(cmap_name="viridis_r")
+ pn.labs(title=wrapped_title,
subtitle=wrapped_subtitle,
caption=wrapped_cap)
+ pn.theme_void()
+ pn.theme(
plot_background=pn.element_rect(fill="#f4f4f4", color="#f4f4f4"),
plot_margin_top=0.03,
plot_margin_right=0.01,
plot_margin_bottom=0.03,
plot_margin_left=0.01,
plot_title=pn.element_text(fontweight="bold"),
plot_caption=pn.element_text(ha="left"),
legend_position="bottom",
legend_key_width=250,
legend_key_height=10,
legend_title=pn.element_blank())
+ pn.coord_fixed()
)
# Save
pn.ggsave(p, filename="map.png", height=7.5, width=5, dpi=300)How well does generative AI translate between Python and R?
ggplot2 code to Python using plotnine, exploring what works well and how much manual tweaking is still needed.
Generative AI is generally pretty good at translating code from one programming language to another - including between R and Python. However, since ggplot2 and plotnine are so similar yet not completely identical, this sometimes causes problems where the differences do exist. There have been several times when I’ve been looking for plotnine help, and have gotten redirected to a ggplot2 solution that doesn’t translate to plotnine.
Plotnine?
There are a few difference between ggplot2 and plotnine syntax because of difference R and Python, including some argument names within functions. There are also some difference defaults, e.g., in the choice colour palettes used. There are also some geoms or coords that don’t quite work in the same way, or don’t exist in both. I wanted to see how well generative AI could translate from plotnine to ggplot2 and whether it would get tripped up on some of these issues.
Original Python map
For the 30 Day Map Challenge, I recently created the following choropleth map using plotnine.
- Housing affordability in England and Wales: 2025
- Housing affordability ratio (ratio of median house price to median gross annual workplace-based earnings) by local authority district in 2025
- Figure 2 Data Download (pre-cleaned and saved as
.csv)
- Local authority districts
- 2025 boundaries BGC, England and Wales
.geojsonfile
There are a couple of things to note about this code:
plotninedoesn’t yet have an implementation ofcoord_sffor properly plotting maps within a coordinate system. In this code, I’ve transformed the data to useEPSG:27700(the British National Grid system) because using this projection with a fixed 1:1 aspect ratio preserves the correct aspect ratio of the map.- The default colour palette in
plotninefor continuous colour gradient is a [viridis] palette. However, it has darker colours for smaller values and it’s more intuitive to map it in reverse. Addingscale_fill_cmap(cmap_name="viridis_r")isn’t done to specifically use a viridis palette, it’s to change the direction only. - I’ve used
textwrapto make sure the title, subtitle, and caption don’t get cut off. In R, extension packages likeggtextormarqueewould be used to wrap the text automatically instead.
Prompt
I used the following prompt with Claude Sonnet 5.5:
Translate this code to use ggplot2 in R instead of Plotnine in Python.
Outputs
Let’s see what that gave us.
R code
Here’s the R code it produced:
library(sf)
library(readr)
library(dplyr)
library(ggplot2)
library(stringr)
ratios <- read_csv("data/affordability.csv")
gdf <- st_read("data/lad.geojson") |>
filter(str_starts(LAD25CD, "E|W")) |>
st_transform(27700)
gdf <- gdf |>
left_join(ratios, by = c("LAD25CD" = "Local authority code")) |>
mutate(`2025` = as.numeric(`2025`))
title_text <- "The number of local authority areas with an affordability ratio above 12 has more than halved since 2021"
wrapped_title <- str_wrap(title_text, width = 55)
st_text <- "Housing affordability ratio by local authority district, England and Wales, 2025"
wrapped_subtitle <- str_wrap(st_text, width = 70)
cap_text <- "Housing affordability ratio, earnings, and house sales prices by local authority district, England and Wales, 1997 to 2025"
wrapped_cap <- str_wrap(cap_text, width = 80)
p <- ggplot() +
geom_sf(
data = gdf,
mapping = aes(fill = `2025`),
colour = "#f4f4f4",
linewidth = 0.1
) +
scale_fill_viridis_c(direction = -1) +
labs(
title = wrapped_title,
subtitle = wrapped_subtitle,
caption = wrapped_cap
) +
theme_void() +
theme(
plot.background = element_rect(fill = "#f4f4f4", colour = "#f4f4f4"),
plot.margin = margin(t = 20, r = 10, b = 20, l = 10),
plot.title = element_text(face = "bold"),
plot.caption = element_text(hjust = 0),
legend.position = "bottom",
legend.key.width = unit(10, "cm"),
legend.key.height = unit(0.4, "cm"),
legend.title = element_blank()
)
ggsave(
filename = "map.png",
plot = p,
height = 7.5,
width = 5,
dpi = 300
)and the additional notes that came with it:
Notes:
- geom_sf() replaces geom_map() and applies coord_sf(), which fixes the aspect ratio, so coord_fixed() isn’t needed.
- Legend key width of 10 cm is more than the 5 inch plot width; reduce it to about 4 cm to fit. Plotnine’s 250 was in points, so unit(250, “pt”) would be a closer match, though it’s still wide for a 5-inch plot.
- plot.margin values are approximated from plotnine’s fractional figure units.
At first glance the code looks okay, and there’s nothing that seems incorrect from just looking at it. It also runs without any errors.
Map
The code produces the following map:
Overall, it looks fairly similar. The only two things that need to be fixed are:
The title is cropped slightly on the right hand side. The font size and wrapping itself is actually okay, it’s just that the margins on the left hand side are a little bit bigger and that pushes the title across. The bullet points that accompanied the code highlight that the plot margins are approximated so we’re already given a heads up that it might be something to look at. To be honest, it’s a reasonably good approximation. We can fix it easily by reducing the margin a little to
margin(t = 10, r = 5, b = 10, l = 5).The legend sizing is off. Again, the bullet points provided after the translated code did highlight the legend sizing as an issue. Another simple fix which is to reduce the legend width to
legend.key.width = unit(1.5, "cm").
With those two minor changes, the code produces the following map
Summary
A few of my main takeaways from this experiment:
- Overall, it translated very well from Python to R. The code ran and recreated the map with a pretty high degree of accuracy. This means that it’s perfectly sensible to draft solutions or prototype in the language you feel comfortable with (i.e. the language you think in) and then translate it if needed.
- The few tweaks I did have to make were mainly due to visual differences in the maps and making sure text and legends look nice which is naturally a more manual, human task of putting on the finishing touches.
- Some of the choices it replicated but didn’t need to, e.g. changing to the British National Grid coordinate system and using the viridis palette, are things I might not necessarily have done if I were writing the R code from scratch. My input code was mostly uncommented, so generative AI can’t (yet) read my mind about whether I was using the viridis function to explicitly use the viridis palette or simply to switch the direction. However, it did correctly set the palette direction in R. I already know I should write more comments in my code (don’t we all?) but maybe this is a more immediate reason to do it rather than just to make my own life easier six months from now.
- Obviously, this is only one experiment with one model, but the model used was Claude’s Medium model which is described as the most efficient for simple tasks and works very well. So you can definitely get away with using lower-power models.
- I’m planning to repeat a similar experiment translating from
ggplot2toplotnine. There’s a lot more documentation onggplot2out there, so I suspect it’s a bit easier to translate toggplot2than toplotninewhich is newer and so would have fewer examples in training data.
plotnine?
This blog post walks you through the process of creating a customised, annotated area chart - showing you how to wrap text, highlight text, and convert from plotnine to matplotlib.
Reuse
Citation
@online{rennie2026,
author = {Rennie, Nicola},
title = {How Well Does Generative {AI} Translate Between {Python} and
{R?}},
date = {2026-11-30},
url = {https://nrennie.rbind.io/blog/plotnine-ggplot2-generative-ai/},
langid = {en}
}


