首页 > 解决方案 > 在 matplotlib 中仅对一些带有箱线图的框进行样式化

问题描述

您将如何更改 matplotlib 箱线图中仅某些框的样式?下面,您可以看到一个样式示例,但我希望该样式仅适用于其中一个框。

示例箱线图

标签: matplotlib

解决方案


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

这意味着如果bplot = ax.boxplot(..)是您的箱线图,您可以通过 访问这些框bplot['boxes'],选择其中一个并将其线型设置为您想要的。例如

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

修改boxplot_color 示例

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()

在此处输入图像描述


推荐阅读