gpt4 book ai didi

python-2.7 - Seaborn 箱线图框从 Python 列表中分配自定义边缘颜色

转载 作者:行者123 更新时间:2023-12-04 14:29:41 25 4
gpt4 key购买 nike

我正在尝试更改 Seaborn 箱线图中方框的外观。我希望所有框都是透明的,并希望从列表中指定框边框。这是我正在使用的代码:

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()

post显示如何更改单个框的颜色和框边缘颜色。但是,我想根据这样的列表分配框边缘颜色 box_line_col = ['r','g',b','purple']。上面的代码在图中产生了 4 个框 - 我想从第一个(最左边的)框开始分配自定义框的边缘颜色,一直到最后一个(最右边的)框。

是否可以从列表中指定框的边缘颜色,同时保持框本身透明(facecolor = white)?

最佳答案

遍历这些框并设置它们的颜色应该可行。在代码的末尾,就在 plt.show() 之前添加:

box_line_col = ['r','g','b','purple'] # As many boxplots as you have

for i,box_col in enumerate(box_line_col):
mybox = g.artists[i] # Or g.patches, in newer versions
# Might want to skip any Rectangles (from legend)
mybox.set_edgecolor(box_col)
mybox.set_facecolor(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()

第一部分基于您引用的帖子, mustache 着色说明来自 this post .

关于python-2.7 - Seaborn 箱线图框从 Python 列表中分配自定义边缘颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37199780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com