簡體   English   中英

更改 seaborn boxplot 線彩虹顏色

[英]Change seaborn boxplot line rainbow color

我在網上找到了這個漂亮的圖表(顯然是用 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調色板。 我怎樣才能做到這一點? (以及附加:我將如何更改線寬?)

考慮兩個 SO 解決方案:

  1. @tmdavison編輯 Line2D 對象的線和點顏色的解決方案
  2. @IanHincks對邊框的明/暗 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM