I'm tring my best to draw a grouped boxplot similar to the following. There is no filling in the box and different types of whisker&edge have different colors:
Sample code:
- generate dataframe for boxplot
x, y, category = list(), list(), list()
for i in range(5):
for j in range(10):
for k in ['Yes', 'No']:
x.append(i)
y.append(np.random.rand(1)[0])
category.append(k)
df_for_boxplot = pd.DataFrame({
'X': x,
'Y': y,
'category': category
})
- box plot with seaborn
sns.set_theme(style="ticks", palette="pastel")
ax = sns.boxplot(x="X", y="Y", data=df_for_boxplot,
hue="category",
# boxprops={"edgecolor": "r"}, # This makes all edges turn blue but I wanna set different catograys in different color.
palette=['w','w'],
whiskerprops={'linestyle':'--'}, showcaps = False)
# Select some boxes in particular by indexing ax.artists and set the edgecolor
[ax.artists[i].set_edgecolor('r') for i in [0,2,4,6,8]]
[ax.artists[i].set_edgecolor('b') for i in [1,3,5,7,9]]
# I can also change the color of specific line but it can only be set artificially.:
ax.lines[0].set_color('r')
ax.legend(loc='upper left')
- The result: sample.png
I can only manually set the color of edge and whisker by indexing ax.artists and ax.lines because I don't know how to uniformly set different categories of boxes. It is difficult to set it manually when there are too many boxes in the image or the data is too complicated.
Is there a more efficient solution? Any suggestions would be appreciated!
(I'm sorry about can't post images because I'm new here and my poor English)