Custom theme with plotnine

logo of a chart:ScatterPlot

Plotnine is a Python library allowing to create beautiful ggplot-like plots using the grammar of graphics syntax.

In this post, we will see how to change theme using plotnine.

Libraries

For creating this chart, we will need to load the following libraries:

import pandas as pd
from plotnine import *

Dataset

Since scatter plot is a type of chart that displays values for two numerical variables for a set of data, we will load the iris dataset:

url = 'https://raw.githubusercontent.com/holtzy/The-Python-Graph-Gallery/master/static/data/iris.csv'
df = pd.read_csv(url)

Default theme

The plotnine default theme is the same as the ggplot2 default theme in R:

(
ggplot(df, aes(x='sepal_length', y='sepal_width')) +
    geom_point()
)

White background theme

There are various theme with white background in plotnine.

Here is an example of the theme_minimal() theme:

(
ggplot(df, aes(x='sepal_length', y='sepal_width')) +
    geom_point() +
    theme_minimal()
)

Dark background theme

If you're looking for a dark background theme, you can use the theme_dark() theme:

(
ggplot(df, aes(x='sepal_length', y='sepal_width')) +
    geom_point() +
    theme_dark()
)

Empty theme

If you want to remove all the elements of the theme, you can use the theme_void() theme:

(
ggplot(df, aes(x='sepal_length', y='sepal_width')) +
    geom_point() +
    theme_void()
)

Themes with grid

If you want to add a grid to your plot, you can use the theme_classic() theme:

(
ggplot(df, aes(x='sepal_length', y='sepal_width')) +
    geom_point() +
    theme_classic()
)

Theme with full grid

If you want to add a full grid to your plot, you can use the theme_bw() theme:

(
ggplot(df, aes(x='sepal_length', y='sepal_width')) +
    geom_point() +
    theme_bw()
)

Going further

This article explains how to change theme in a plot made with plotnine.

If you want to go further, you can also check this introduction to scatter plot with plotnine

Contact & Edit


👋 This document is a work by Yan Holtz. You can contribute on github, send me a feedback on twitter or subscribe to the newsletter to know when new examples are published! 🔥

This page is just a jupyter notebook, you can edit it here. Please help me making this website better 🙏!