pandas 设置箱形图'boxes'面色透明度

jdzmm42g  于 2023-10-14  发布在  其他
关注(0)|答案(2)|浏览(139)

我正在寻找一种方法来设置透明度的箱线图面色。现在它显示为“红色”,alpha=1。我如何改变它为'红色'与alpha为0.5,例如,同时保持框的边缘颜色不透明的'黑色'?我只需要面色的透明度,而不是边色的透明度。有什么想法吗?

验证码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as cls
import matplotlib

matplotlib.interactive(True)

df = pd.DataFrame({"A": [18,28,29,32,35,36,37,37,39,40,42,42,46,48,54,56,57,61,61,62,63,65],
                   "B":  [9,13,17,15,23,21,24,28,26,30,29,30,38,42,40,48,40,51,54,50,51,57],
                   "C": [1,98,65,47,58,95,24,5,63,7,41,5,6,84,56,96,33,25,61,94,68,83]})

columns = ['A', 'B']
df_data = df.loc[:, columns]

def boxplot(y_lims, y_lime):
    plt.figure(figsize=((12.0 / 2.54), (7.42 / 2.54)), facecolor=None, edgecolor='black')  
    fig, ax = plt.subplots() 
    boxprops = dict(linestyle='-', linewidth=0.6)  
    bp = df_data.boxplot(ax=ax, grid=False, showfliers=False, boxprops=boxprops, showmeans=True, return_type='dict', patch_artist=True)
    [patch.set(facecolor='red', alpha=1.0) for patch in bp['boxes']]   #if alpha=0.5; both face and edge color are transparent, I only want the facecolor to be transparent 
    [patch.set_edgecolor('black') for patch in bp['boxes']]
    [item.set_color('black') for item in bp['whiskers']]
    [item.set_color('black') for item in bp['caps']]
    [item.set_marker('.') for item in bp['means']]
    [item.set_markerfacecolor('black') for item in bp['means']]
    [item.set_markeredgecolor('black') for item in bp['means']]
    [item.set_color('black') for item in bp['medians']]

    ax.set_ylim(y_lims, y_lime)    
    plt.show()

if __name__ == '__main__':

    Boxplot_a = boxplot(None, None)

注意:- rgba-colors并没有做到这一点,alpha由于某种原因无法识别

scyqe7ek

scyqe7ek1#

一旦为整个路径面片设置了alpha,RGBA边缘和面颜色中可能的alpha值将被忽略。Pandas在内部将alpha设置为1
因此,为了使其工作,您需要将alpha重置为None,然后根据需要指定颜色中的alpha通道(例如,0.5用于正面,1用于边缘颜色):

[patch.set(alpha=None, facecolor=(1,0,0,.5)) for patch in bp['boxes']]

**编辑:**这已经是fixed,将在1.1.0版本中提供(第三项)。那么你可以简单地做

boxprops = dict(linestyle='-', linewidth=0.6, facecolor=(1,0,0,.5), edgecolor='k')

(no之后需要更换补丁)

guicsvcw

guicsvcw2#

set_alpha同时更改面颜色和边颜色,为避免这种情况,您可能需要考虑将RGBA值直接传递给面颜色。

相关问题