python matplotlib filled boxplots

MHardy picture MHardy · Nov 29, 2013 · Viewed 20.8k times · Source

Does anyone know if we can plot filled boxplots in python matplotlib? I've checked http://matplotlib.org/api/pyplot_api.html but I couldn't find useful information about that.

Answer

Joe Kington picture Joe Kington · Nov 29, 2013

The example that @Fenikso shows an example of doing this, but it actually does it in a sub-optimal way.

Basically, you want to pass patch_artist=True to boxplot.

As a quick example:

import matplotlib.pyplot as plt
import numpy as np

data = [np.random.normal(0, std, 1000) for std in range(1, 6)]
plt.boxplot(data, notch=True, patch_artist=True)

plt.show()

enter image description here

If you'd like to control the color, do something similar to this:

import matplotlib.pyplot as plt
import numpy as np

data = [np.random.normal(0, std, 1000) for std in range(1, 6)]

box = plt.boxplot(data, notch=True, patch_artist=True)

colors = ['cyan', 'lightblue', 'lightgreen', 'tan', 'pink']
for patch, color in zip(box['boxes'], colors):
    patch.set_facecolor(color)

plt.show()

enter image description here