ggplot styles in Python

Question:

When I look at the plotting style in the Pandas documentation, the plots look different from the default one. It seems to mimic the ggplot “look and feel”.

Same thing with the seaborn’s package.

How can I load that style? (even if I am not using a notebook?)

Asked By: Josh

||

Answers:

Update: If you have matplotlib >= 1.4, there is a new style module which has a ggplot style by default. To activate this, use:

from matplotlib import pyplot as plt
plt.style.use('ggplot')

To see all the available styles, you can check plt.style.available.


Similarly, for seaborn styling you can do:

plt.style.use('seaborn-white')

or, you can use seaborn‘s own machinery to set up the styling:

import seaborn as sns
sns.set()

The set() function has more options to select a specific style (see docs). Note that seaborn previously did the above automatically on import, but with the latest versions (>= 0.8) this is no longer the case.


If you actually want a ggplot-like syntax in Python as well (and not only the styling), take a look at the plotnine package, which is a grammar of graphics implementation in Python with a syntax very similar to R’s ggplot2.


Note: the old answer mentioned to do pd.options.display.mpl_style = 'default'
. This was however deprecated in pandas in favor of matplotlib’s styling using plt.style(..), and in the meantime this functionality is even removed from pandas.

Answered By: joris

For the themes in python-ggplot, you can use them with other plots:

from ggplot import theme_gray
theme = theme_gray()
with mpl.rc_context():
    mpl.rcParams.update(theme.get_rcParams())

    # plotting commands here

    for ax in plt.gcf().axes:
        theme.post_plot_callback(ax)
Answered By: Jan Katins

While I think that joris answer is a better solution since you’re using Pandas, it should be mentioned that Matplotlib can be set to mimic ggplot by issuing the command matplotlib.style.use('ggplot').

See examples in the Matplotlib gallery.

Answered By: AllanLRH

If you need to see available styles :

import matplotlib.pyplot as plt

print(plt.style.available)

This will print available styles.

And use this link to select the style you prefer

https://tonysyu.github.io/raw_content/matplotlib-style-gallery/gallery.html

Answered By: Vibhutha Kumarage

Jan Katins’s answer is good, but the python-ggplot project seems to have become inactive. The plotnine project is more developed and supports an analogous, but superficially different, solution:

from plotnine import theme_bw
import matplotlib as mpl
theme = theme_bw()

with mpl.rc_context():
    mpl.rcParams.update(theme.rcParams)
Answered By: groceryheist
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.