箱线图中的填充箱颜色

Fill Box Color in Box Plot

我一直在尝试用不同的颜色填充一组箱线图的箱子。请参阅下面的代码。

# Box Plots
fig, axs = plt.subplots(2, 2, figsize = (10,10))
plt.subplots_adjust(hspace = .2,wspace = 0.4)
plt.tick_params(axis='x', which='both', bottom=False)

axs[0,0].boxplot(dfcensus["Median Age"],patch_artist=True)
axs[0,0].set_ylabel('Age', fontsize = '12')
axs[0,0].set_title('Median Age', fontsize = '16')
axs[0,0].get_xaxis().set_visible(False)
axs[0,0].set_facecolor('blue')

axs[0,1].boxplot(dfcensus["% Bachelor Degree or Higher"],patch_artist=True)
axs[0,1].set_ylabel('Percentage', fontsize = '12')
axs[0,1].set_title('% Bachelor Degree or Higher', fontsize = '16')
axs[0,1].get_xaxis().set_visible(False)
axs[0,1].set_facecolor('red')

axs[1,0].boxplot(dfcensus["Median Household Income"],patch_artist=True)
axs[1,0].set_ylabel('Dollars', fontsize = '12')
axs[1,0].set_title('Median Household Income', fontsize = '16')
axs[1,0].get_xaxis().set_visible(False)
axs[1,0].set_facecolor('green')

axs[1,1].boxplot(dfcensus["Median Home Value"],patch_artist=True)
axs[1,1].set_ylabel('Dollars', fontsize = '12')
axs[1,1].set_title('Median Home Value', fontsize = '16')
axs[1,1].get_xaxis().set_visible(False)
axs[1,1].set_facecolor=('orange')

plt.show()

它填充了框架,而不是填充箱形图中的方框。

This is a picture of the output

感谢您的帮助。

添加功能 add_color 将帮助您解决问题。请看下面的代码。

注意:您还可以为箱线图中的每个元素赋予不同的颜色,例如 boxes 是绿色,whiskers 是蓝色等。

import matplotlib.pyplot as plt

dummy_data = [1,2,3,4]

def add_color(bp, color):
    for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
        plt.setp(bp[element], color=color)

# Box Plots
fig, axs = plt.subplots(2, 2, figsize = (10,10))
plt.subplots_adjust(hspace = .2,wspace = 0.4)
plt.tick_params(axis='x', which='both', bottom=False)

bp_1 = axs[0,0].boxplot(dummy_data,patch_artist=True)
axs[0,0].set_ylabel('Age', fontsize = '12')
axs[0,0].set_title('Median Age', fontsize = '16')
axs[0,0].get_xaxis().set_visible(False)
add_color(bp_1, "blue")

bp_2 = axs[0,1].boxplot(dummy_data, patch_artist=True)
axs[0,1].set_ylabel('Percentage', fontsize = '12')
axs[0,1].set_title('% Bachelor Degree or Higher', fontsize = '16')
axs[0,1].get_xaxis().set_visible(False)
add_color(bp_2, "red")

bp_3 = axs[1,0].boxplot(dummy_data, patch_artist=True)
axs[1,0].set_ylabel('Dollars', fontsize = '12')
axs[1,0].set_title('Median Household Income', fontsize = '16')
axs[1,0].get_xaxis().set_visible(False)
add_color(bp_3, "green")

bp_4 = axs[1,1].boxplot(dummy_data,patch_artist=True)
axs[1,1].set_ylabel('Dollars', fontsize = '12')
axs[1,1].set_title('Median Home Value', fontsize = '16')
axs[1,1].get_xaxis().set_visible(False)
add_color(bp_4, "orange")

plt.show()

情节: