我正在尽我最大的努力绘制一个类似于下面的分组框图。盒子里没有填充,不同类型的晶须和边缘有不同的颜色:
示例代码:
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
})
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')
我只能通过索引ax.artists和ax.lines手动设置边缘和晶须的颜色,因为我不知道如何统一设置不同类别的框。当图像中有太多的框或数据太复杂时,很难手动设置它。
有没有更有效的解决方案?如有任何建议,将不胜感激!
(我很抱歉不能发照片,因为我是新来的,我的英语很差)
发布于 2022-01-01 11:04:08
这里的极好的回答没有解决这个问题。
我做了一些研究,并将方框、填充和其他行从ax.Patches改为PathPatch,我正在等待更熟悉这类事情的人关于为什么不能在ax.artists中解决这个问题的建议。
fig, ax = plt.subplots(figsize=(12,9))
#sns.set_theme(style="ticks", palette="pastel")
sns.boxplot(x="X", y="Y",
data=df_for_boxplot,
hue="category",
# boxprops={"edgecolor": "r"},
# palette=['w','w'],
whiskerprops={'linestyle':'--'},
# showcaps=False,
ax=ax
)
p = 0
for box in ax.patches:
#print(box.__class__.__name__)
if box.__class__.__name__ == 'PathPatch':
if p % 2 == 0:
box.set_edgecolor('C1')
box.set_facecolor('white')
for k in range(6*p,6*(p+1)):
ax.lines[k].set_color('C1')
p += 1
else:
box.set_edgecolor('C0')
box.set_facecolor('white')
for k in range(6*p,6*(p+1)):
ax.lines[k].set_color('C0')
p +=1
for legpatch in ax.get_legend().get_patches():
col = legpatch.get_facecolor()
legpatch.set_edgecolor(col)
legpatch.set_facecolor('None')
plt.show()
https://stackoverflow.com/questions/70532796
复制相似问题