Seaborn boxplot box assign custom edge colors from

2019-07-11 07:12发布

问题:

I am trying to change the appearance of boxes in Seaborn's boxplot. I would like all boxes to be transparent and for the box borders to be specified from a list. Here is the code I am working with:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
fig, ax = plt.subplots()

df = pd.DataFrame(np.random.rand(10,4),columns=list('ABCD'))
df['E'] = [1,2,3,1,1,4,3,2,3,1]

sns.boxplot(x=df['E'],y=df['C'])

# Plotting the legend outside the plot (above)
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
handles, labels = ax.get_legend_handles_labels()
leg = plt.legend(handles[0:2], labels[0:2],
                               loc='upper center', bbox_to_anchor=(0.5, 1.10), ncol=2)
plt.show()

This post shows how to change the color and box edgecolor of one single box. However, I would like to assign box edgecolors based on a list like this box_line_col = ['r','g',b','purple']. The above code produces 4 boxes in the plot - I would like to assign custom box edge colors starting from the first (leftmost) box and continuing through to the last (rightmost) box.

Is it possible to to specify the box edge colors from a list, while keeping the boxes themselves transparent (facecolor = white)?

回答1:

Looping through the boxes and setting their colors should work. At the end of your code, just before plt.show() add:

box_line_col = ['r','g','b','purple']

for i,box_col in enumerate(box_line_col):
    mybox = g.artists[i]
    mybox.set_edgecolor(box_col)
    mybox.set_fccecolor(None) #or white, if that's what you want

    # If you want the whiskers etc to match, each box has 6 associated Line2D objects (to make the whiskers, fliers, etc.)
    # Loop over them here, and use the same colour as above
    for j in range(i*6,i*6+6):
        line = g.lines[j]
        line.set_color(box_col)
        line.set_mfc(box_col)
        line.set_mec(box_col)

plt.show()

The first part is based on the post you referenced and and the whisker-coloring directions came from this post.