Face pattern for boxes in boxplots

2019-02-18 12:03发布

问题:

I would like to do something of the sort (using matplotlib):

(from Colorfill boxplot in R-cran with lines, dots, or similar)

I saw some info about hatch(ing)? But I really can't make heads or tails on how to use this.

Also I find myself wondering how can I change parameters like the possible attributes of a boxprop dict -- used in plt.boxplot(..., boxprops=boxpropsdict). Is it possible to just have a list of all the possible attributes for this?

回答1:

The important aspect is to set patch_artist=True when calling boxplot.

import numpy as np
import matplotlib.pyplot as plt

# fake up some data
spread= np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low), 0)

# basic plot
bp = plt.boxplot(data, patch_artist=True)

for box in bp['boxes']:
    # change outline color
    box.set(color='red', linewidth=2)
    # change fill color
    box.set(facecolor = 'green' )
    # change hatch
    box.set(hatch = '/')

plt.show()

The basic plot example is taken from the boxplot demo. However, none of those examples set patch_artist=True. If that statement is omitted, you will get this error:

AttributeError: 'Line2D' object has no attribute 'set_facecolor'

The boxplot demo 2 shows in great detail, how rectangles can be fitted to the boxplot in order to obtain coloring. This blog points to the option of the patch_artist.
For more ideas about hatches, refer to the hatch demo. The example above produces this figure: