重要的方面是在调用boxplot时设置patch_artist = True.
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()
基本的绘图示例取自boxplot demo.但是,这些示例都没有设置patch_artist = True.如果省略该语句,您将收到此错误:
AttributeError: ‘Line2D’ object has no attribute ‘set_facecolor’
boxplot demo 2非常详细地展示了如何将矩形拟合到箱线图以获得着色. This blog指向patch_artist的选项.
有关阴影线的更多想法,请参阅hatch demo.上面的示例生成此图: