要为箱线图着色,您需要首先使用patch_artist=True 关键字告诉它箱是补丁,而不仅仅是路径。那么这里有两个主要选项:
- 通过
...props关键字参数设置颜色,例如
boxprops=dict(facecolor="red")。对于所有关键字参数,请参阅the documentation
- 使用
plt.setp(item, properties) 功能设置方框、胡须、传单、中位数、大写字母的属性。
- 从返回的字典中获取盒子的各个项目,并在它们上单独使用
item.set_<property>(...)。此选项在以下问题的答案中有详细说明:python matplotlib filled boxplots,它允许单独更改各个框的颜色。
完整示例,显示选项 1 和 2:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.normal(0.1, size=(100,6))
data[76:79,:] = np.ones((3,6))+0.2
plt.figure(figsize=(4,3))
# option 1, specify props dictionaries
c = "red"
plt.boxplot(data[:,:3], positions=[1,2,3], notch=True, patch_artist=True,
boxprops=dict(facecolor=c, color=c),
capprops=dict(color=c),
whiskerprops=dict(color=c),
flierprops=dict(color=c, markeredgecolor=c),
medianprops=dict(color=c),
)
# option 2, set all colors individually
c2 = "purple"
box1 = plt.boxplot(data[:,::-2]+1, positions=[1.5,2.5,3.5], notch=True, patch_artist=True)
for item in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:
plt.setp(box1[item], color=c2)
plt.setp(box1["boxes"], facecolor=c2)
plt.setp(box1["fliers"], markeredgecolor=c2)
plt.xlim(0.5,4)
plt.xticks([1,2,3], [1,2,3])
plt.show()