【问题标题】:Customize colors in Python by Hue & category在 Python 中按色调和类别自定义颜色
【发布时间】:2021-12-28 00:42:27
【问题描述】:

我有一个包含两个类别的数据框:女性和男性,以及 2 年。我想要的是在同一个图中有两个类别,但按图的特定颜色(可以是条形图或箱线图)。

我的代码是:

test =pd.DataFrame([[2021, 'female', 3], [2021, 'male', 1], [2021, 'female', 6],
                    [2021, 'female', 3], [2021, 'male', 4], [2021, 'female', 10],
                    [2020, 'female', 2], [2020, 'male', 9], [2020, 'male', 7],
                    [2020, 'female', 1], [2020, 'male', 5], [2020, 'male', 8]
                   ], columns=['Year', 'category', 'value'])

plt.figure(figsize=(20,8))
g = sns.boxplot(y='value', x='category', data=test, hue='Year')
g.set_xticklabels(g.get_xmajorticklabels(), fontsize = 12)

而mi当前输出为:

我期望拥有的是这样的:

如果我能自动获得这个情节,那么更改库不是问题。

【问题讨论】:

    标签: python-3.x matplotlib seaborn


    【解决方案1】:

    我不知道有哪个库可以开箱即用地进行这种着色。使用 seaborn boxplot,您可以遍历生成的框并分配单独的颜色和透明度。自定义图例可以通过灰色阴影显示透明度:

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    test = pd.DataFrame([[2021, 'female', 3], [2021, 'male', 1], [2021, 'female', 6],
                         [2021, 'female', 3], [2021, 'male', 4], [2021, 'female', 10],
                         [2020, 'female', 2], [2020, 'male', 9], [2020, 'male', 7],
                         [2020, 'female', 1], [2020, 'male', 5], [2020, 'male', 8]
                         ], columns=['Year', 'category', 'value'])
    
    plt.figure(figsize=(20, 8))
    sns.set_style('white')
    ax = sns.boxplot(y='value', x='category', data=test, hue='Year')
    ax.tick_params(axis='x', labelsize=14)
    
    hue_values = np.sort(test['Year'].unique())
    num_hue_values = len(hue_values)
    colors = ['crimson', 'dodgerblue']
    min_alpha = 0.3
    max_alpha = 0.6
    alphas = np.linspace(min_alpha, max_alpha, num_hue_values)
    for i, box in enumerate(ax.artists):
        box.set_facecolor(colors[i // num_hue_values])
        box.set_alpha(alphas[i % num_hue_values])
    handles = [plt.Rectangle((0, 0), 0, 0, facecolor='black', edgecolor='black', alpha=alpha, label=label)
               for alpha, label in zip(alphas, hue_values)]
    ax.legend(handles=handles)
    plt.show()
    

    这是另一个具有更多色调类别的示例:

    tips = sns.load_dataset('tips')
    
    plt.figure(figsize=(20, 8))
    sns.set_style('white')
    ax = sns.boxplot(y='total_bill', x='sex', data=tips, hue='day')
    ax.tick_params(axis='x', labelsize=14)
    
    hue_values = tips['day'].cat.categories
    num_hue_values = len(hue_values)
    colors = ['lime', 'purple']
    min_alpha = 0.3
    max_alpha = 0.6
    alphas = np.linspace(min_alpha, max_alpha, num_hue_values)
    for i, box in enumerate(ax.artists):
        box.set_facecolor(colors[i // num_hue_values])
        box.set_alpha(alphas[i % num_hue_values])
    handles = [plt.Rectangle((0, 0), 0, 0, facecolor='black', edgecolor='black', alpha=alpha, label=label)
               for alpha, label in zip(alphas, hue_values)]
    ax.legend(handles=handles)
    sns.despine()
    plt.show()
    

    【讨论】:

    • 如果这回答了您的问题,您可以考虑投票和/或marking 它被接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 2020-12-07
    • 2015-06-29
    相关资源
    最近更新 更多