How to Use ggplot Styles in Matplotlib Plots

One of the most popular data visualization packages in the R programming language is ggplot2.

To apply ggplot2 styling to a plot created in Matplotlib, you can use the following syntax:

import matplotlib.pyplot as plt'ggplot')

The following example shows how to use this syntax in practice.

Example: Using ggplot Styles in Matplotlib Plots

Suppose we have a NumPy array with 1,000 values:

import numpy as np

#make this example reproducible.

#create numpy array with 1000 values that follow normal dist with mean=10 and sd=2
data = np.random.normal(size=1000, loc=10, scale=2)

#view first five values

array([13.24869073,  8.77648717,  8.9436565 ,  7.85406276, 11.73081526])

We can use the following code to create a histogram in Matplotlib to visualize the distribution of values in the NumPy array:

import matplotlib.pyplot as plt

#create histogram
plt.hist(data, color='lightgreen', ec='black', bins=15)

To apply ggplot2 styling to this histogram, we can use plt.syle.use(‘ggplot’) as follows:

import matplotlib.pyplot as plt

#specify ggplot2 style'ggplot')

#create histogram with ggplot2 style
plt.hist(data, color='lightgreen', ec='black', bins=15)

matplotib ggplot2 style

The histogram now has the style of a plot created in ggplot2.

Namely, this style adds a light grey background with white gridlines and uses slightly larger axis tick labels.

Note that we applied ggplot2 styling to a histogram, but the statement‘ggplot’) can be used to apply ggplot2 styling to any plot in Matplotlib.

Note: You can find more style sheets available to use in Matplotlib plots here.

Additional Resources

The following tutorials explain how to create other common charts in Python:

How to Create Stacked Bar Charts in Matplotlib
How to Create a Relative Frequency Histogram in Matplotlib
How to Create a Horizontal Barplot in Seaborn

Featured Posts

Leave a Reply

Your email address will not be published. Required fields are marked *