To adjust the colours of your boxes in pandas.boxplot
, you have to adjust your code slightly. First of all, you have to tell boxplot
to actually fill the boxes with a colour. You do this by specifying patch_artist = True
, as is documented here. However, it appears that you cannot specify a colour (default is blue) -- please anybody correct me if I'm wrong. This means you have to change the colour afterwards. Luckily pandas.boxplot
offers an easy option to get the artists in the boxplot as return value by specifying return_type = 'both'
see here for an explanation. What you get is a pandas.Series
with keys according to your DataFrame
columns and values that are tuples containing the Axes
instances on which the boxplots are drawn and the actual elements of the boxplots in a dictionary. I think the code is pretty self-explanatory:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D'])
df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4', 'model5', 'model6', 'model7'], 20))
bp_dict = df.boxplot(
by="models",layout=(4,1),figsize=(6,8),
return_type='both',
patch_artist = True,
)
colors = ['b', 'y', 'm', 'c', 'g', 'b', 'r', 'k', ]
for row_key, (ax,row) in bp_dict.iteritems():
ax.set_xlabel('')
for i,box in enumerate(row['boxes']):
box.set_facecolor(colors[i])
plt.show()
The resulting plot looks like this:
Hope this helps.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…