改变seaborn boxplot线彩虹色

问题描述 投票:1回答:1

我在网上找到了这个漂亮的图形(显然是用图表制作的)并想用seaborn重新创建它。 enter image description here

到目前为止这是我的代码:

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)

到目前为止的结果:

enter image description here

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

python visualization seaborn
1个回答
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()

Plot Outputs


对于您的特定绘图,为boxplot设置轴,然后遍历其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)
© www.soinside.com 2019 - 2024. All rights reserved.