在matplotlib中仅使用箱形图样式化一些框

时间:2018-05-16 21:10:11

标签: matplotlib

你如何改变matplotlib boxplot中只有一些盒子的风格?下面,您可以看到样式的示例,但我希望样式仅适用于其中一个框。

Example boxplots

1 个答案:

答案 0 :(得分:1)

同样的问题已经asked for seaborn boxplots了。对于matplotlib箱图,这更容易,因为boxplot直接返回相关艺术家的字典,请参阅boxplot documentation

这意味着如果bplot = ax.boxplot(..)是您的箱形图,您可以通过bplot['boxes']访问这些框,选择其中一个并根据您的需要设置其线条样式。 E.g。

bplot['boxes'][2].set_linestyle("-.")

修改boxplot_color example

import matplotlib.pyplot as plt
import numpy as np

# Random test data
np.random.seed(19680801)
all_data = [np.random.normal(0, std, size=100) for std in range(1, 4)]
labels = ['x1', 'x2', 'x3']

fig, ax = plt.subplots()

# notch shape box plot
bplot = ax.boxplot(all_data, vert=True,  patch_artist=True, labels=labels)

# Loop through boxes and colorize them individually
colors = ['pink', 'lightblue', 'lightgreen']
for patch, color in zip(bplot['boxes'], colors):
    patch.set_facecolor(color)

# Make the third box dotted
bplot['boxes'][2].set_linestyle("-.")
plt.show()

enter image description here