【问题标题】:Change seaborn boxplot line rainbow color更改 seaborn 箱线图线彩虹颜色
【发布时间】:2019-09-03 12:24:51
【问题描述】:

我在网上找到了这张漂亮的图表(显然是用 plotly 制作的),并想用 seaborn 重新创建它。

这是我目前的代码:

import pandas as pd
import seaborn as sns

data = ...

flierprops = dict(marker='o', markersize=3)
sns.boxplot(x="label", y="mean",palette="husl", data=data,saturation=1,flierprops=flierprops)

这是迄今为止的结果:

我已经很高兴了,但我想调整线条和异常颜色以匹配husl 调色板。我怎样才能做到这一点? (以及附加:我将如何更改线宽?)

【问题讨论】:

    标签: python visualization seaborn


    【解决方案1】:

    考虑两种 SO 解决方案:

    1. @tmdavison's solution 编辑 Line2D 对象的线和点颜色
    2. @IanHincks's solution 为边框亮/暗 matplotlib 颜色

    数据

    import numpy as np
    import pandas as pd
    
    data_tools = ['sas', 'stata', 'spss', 'python', 'r', 'julia']
    
    ### DATA BUILD
    np.random.seed(4122018)
    random_df = pd.DataFrame({'group': np.random.choice(data_tools, 500),
                              'int': np.random.randint(1, 10, 500),
                              'num': np.random.randn(500),
                              'bool': np.random.choice([True, False], 500),
                              'date': np.random.choice(pd.date_range('2019-01-01', '2019-04-12'), 500)
                               }, columns = ['group', 'int', 'num', 'char', 'bool', 'date'])
    

    情节 (生成两个:原始和调整)

    import matplotlib.pyplot as plt
    import matplotlib.colors as mc
    import colorsys
    import seaborn as sns
    
    def lighten_color(color, amount=0.5):  
        # --------------------- SOURCE: @IanHincks ---------------------
        try:
            c = mc.cnames[color]
        except:
            c = color
        c = colorsys.rgb_to_hls(*mc.to_rgb(c))
        return colorsys.hls_to_rgb(c[0], 1 - amount * (1 - c[1]), c[2])
    
    # --------------------- SOURCE: @tmdavison ---------------------    
    fig, (ax1,ax2) = plt.subplots(2, figsize=(12,6))                           
    sns.set()
    
    flierprops = dict(marker='o', markersize=3)
    sns.boxplot(x="group", y="num", palette="husl", data=random_df, saturation=1, 
               flierprops=flierprops, ax=ax1)
    ax1.set_title("Original Plot Output")
    
    sns.boxplot(x="group", y="num", palette="husl", data=random_df, saturation=1, 
                flierprops=flierprops, ax=ax2)
    ax2.set_title("\nAdjusted Plot Output")
    
    for i,artist in enumerate(ax2.artists):
        # Set the linecolor on the artist to the facecolor, and set the facecolor to None
        col = lighten_color(artist.get_facecolor(), 1.2)
        artist.set_edgecolor(col)    
    
        # 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 = ax2.lines[j]
            line.set_color(col)
            line.set_mfc(col)
            line.set_mec(col)
            line.set_linewidth(0.5)   # ADDITIONAL ADJUSTMENT
    
    plt.tight_layout()
    plt.show()
    


    对于您的特定情节,为箱线图设置轴,然后遍历其 MPL 艺术家:

    fig, ax = plt.subplots(figsize=(12,6))      
    sns.boxplot(x="label", y="mean",palette="husl", data=data, saturation=1,
                flierprops=flierprops, ax=ax)
    
    for i,artist in enumerate(ax.artists):
        # Set the linecolor on the artist to the facecolor, and set the facecolor to None
        col = lighten_color(artist.get_facecolor(), 1.2)
        artist.set_edgecolor(col)    
    
        # 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 = ax.lines[j]
            line.set_color(col)
            line.set_mfc(col)
            line.set_mec(col)
            line.set_linewidth(0.5)
    

    【讨论】:

    • 太棒了,正是我搜索的内容!
    猜你喜欢
    • 2020-08-28
    • 2020-08-07
    • 2012-05-23
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    相关资源
    最近更新 更多