Seaborn passes kwargs to plt.boxplot()

2019-06-01 03:06发布

问题:

I'm trying to use Seaborn to create a boxplot and a stripplot, as in this example. However, the data points of the stripplot can be hard to read on top of the boxplot. My goal is to have an 'open' boxplot, like the ones made by a pandas DataFrame.plot(kind='box'). See here. But I still want Seaborn's builtin grouping functionality.

My attempt has been to use the PatchArtist rather than the Line2D artist. From the seaborn boxplot documentation,

kwargs : key, value mappings

Other keyword arguments are passed through to plt.boxplot at draw time.

But passing patch_artist = True results in an error: TypeError: boxplot() got multiple values for keyword argument 'patch_artist'.

A minimal working example:

import seaborn as sns
data = sns.load_dataset('tips')
sns.boxplot(x='day', y='total_bill', data=data, **{'notch':True})

The above example shows that the kwargs are being passed properly to plt.boxplot(). The example below generates the TypeError.

import seaborn as sns
data = sns.load_dataset('tips')
sns.boxplot(x='day', y='total_bill', data=data, **{'patch_artist':True})

Is the patch_artist the best way to generate open boxplots? If so, how can I use it with seaborn?

回答1:

As it turns out, seaborn returns the subplot axis that it just generated. We can directly set properties on the artists it creates.

A minimal example:

import seaborn as sns
import matplotlib.pyplot as plt

data = sns.load_dataset('tips')

ax = sns.boxplot(x='day', y='total_bill', data=data)

plt.setp(ax.artists, alpha=.5, linewidth=2, fill=False, edgecolor="k")

sns.stripplot(x='day', y='total_bill', data=data, jitter=True, edgecolor='gray')

This lets us manipulate each patch individually, while still using the hue variable in sns.boxplot() to group the data for us. Finally, the stripplot overlay sits on top of the box.