在箱线图中填充箱线颜色

LDL*_*oue 6 python matplotlib boxplot

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

# 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()
Run Code Online (Sandbox Code Playgroud)

它不是填充箱线图中的框,而是填充框。

这是输出的图片

我很感激你的帮助。

Has*_*maz 5

添加一个功能 asadd_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()

Run Code Online (Sandbox Code Playgroud)

阴谋 : 在此输入图像描述