Python: 设置箱线图中的框背景

Python: set background of a box in a boxplot

我正在使用 matploitlib boxplot 创建如下图:

使用此代码:

# Create a figure instance
fig = plt.figure(1, figsize=(4, 4))

# Create an axes instance
ax = fig.add_subplot(111)
ax.set_ylim([0, 1.2])

# Create the boxplot
bp = ax.boxplot(data_to_plot,widths=(0.5, 0.5))
plt.setp(bp['boxes'], linewidth=1)

# Save the figure
plt.xticks([1, 2], ['A', 'B'],fontsize=16)
plt.yticks(fontsize=16)
#fig.savefig('fig1.png', bbox_inches='tight')
plt.show()

我想做的是为每个框设置背景,使它们具有不同的颜色。

谢谢

这只是部分满足您的要求,但也许它可以帮助您找到问题的答案。您可以使用

bp = ax.boxplot(data_to_plot,widths=(0.5, 0.5),notch=True, patch_artist=True)

填充情节。要更改颜色,请查看此 Example

我最终向箱线图添加了以下参数:

bp = ax.boxplot(data_to_plot,widths=(0.5, 0.5),patch_artist=True)

并使用以下方法为每个框分配独特的颜色:

bp['boxes'][0].set( facecolor = '#1b9e77' )