How can I fill a matplotlib grid?

Viewed 4449

I would like to render a ggplot2 style filled grid, a la this
(source: had.co.nz)

I haven't been able to find any online resources that deal with styling the grid in such a way. Do I have to resort to doing something like plotting my own rectangular patches?

Edit: after trying Chris' solution, I have written a script to help make matplotlib graphs look like ggplot2 if anyone is interested.

http://messymind.net/making-matplotlib-look-like-ggplot/

2 Answers

If you just want to update the grid background for a single chart, you can just do:

from matplotlib import pyplot as plt

fig, ax = plt.subplots()
ax.set_facecolor('#EBEBEB')
# Plot something..

But if you want full ggplot styles for all your charts, Matplotlib comes with a ggplot theme so the easiest way to do this is to enable that:

from matplotlib import pyplot as plt

plt.style.use('ggplot')

Seaborn also has a similar theme:

import seaborn as sns

sns.set_style('darkgrid')

Lastly, you can also set the rcParams manually if you'd prefer:

from matplotlib import pyplot as plt
from matplotlib.ticker import AutoMinorLocator
import numpy as np

# This isn't a full styling but gets you most of the way.
ggplot_styles = {
    'axes.edgecolor': 'white',
    'axes.facecolor': 'EBEBEB',
    'axes.grid': True,
    'axes.grid.which': 'both',
    'axes.spines.left': False,
    'axes.spines.right': False,
    'axes.spines.top': False,
    'axes.spines.bottom': False,
    'font.size': 12,
    'grid.color': 'white',
    'grid.linewidth': '1.4',
    'xtick.color': '555555',
    'xtick.major.bottom': True,
    'xtick.minor.bottom': False,
    'ytick.color': '555555',
    'ytick.major.left': True,
    'ytick.minor.left': False,
}

plt.rcParams.update(ggplot_styles)

# Plot an example chart.
fig, ax = plt.subplots(figsize=(9, 6))
x = np.linspace(0, 14, 100)
for i in range(1, 7):
    ax.plot(x, np.sin(x + i * .5) * (7 - i))

# Set minor ticks/gridline cadence.
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))

# Turn minor gridlines on and make them thinner.
ax.grid(which='minor', linewidth=0.5)

matplotlib plot with ggplot style

Related