【问题标题】:How do I create a fixed color map in Seaborn/Matplotlib (min value = Red, max value = Green)如何在 Seaborn/Matplotlib 中创建固定颜色图(最小值 = 红色,最大值 = 绿色)
【发布时间】:2020-07-29 06:49:41
【问题描述】:

我正在尝试创建一个固定的颜色图以用作 seaborn 点图中的调色板。我目前的代码如下:

        my_cmap2 = matplotlib.colors.LinearSegmentedColormap.from_list("", ['red', 'orange', 'gold' ,'yellow', 'greenyellow', 'lime', 'green'])
        matplotlib.cm.register_cmap("mycolormap", my_cmap2)
        cpal = sns.color_palette("mycolormap", n_colors=10, desat=1)
        
        ax = sns.pointplot(x="Rank", y="Yld_Vol_Dr", data=df, hue="Rank", palette=cpal)

我需要将最小值(等级)始终固定为红色,将最大值(等级)固定为绿色。如果我最多有 10 个等级,我当前的代码就可以工作,但是如果我缺少任何数据(例如等级 2),那么我就无法获得所需的全色标。

如何将红色/绿色设置为固定最小值/最大值?

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    hue_order 可用于强制显示所有色调值(并设置它们的顺序)。

    from matplotlib import pyplot as plt
    from matplotlib.colors import LinearSegmentedColormap
    import seaborn as sns
    import numpy as np
    
    my_cmap2 = LinearSegmentedColormap.from_list("", ['red', 'orange', 'gold', 'yellow', 'greenyellow', 'lime', 'green'])
    plt.cm.register_cmap("mycolormap", my_cmap2)
    cpal = sns.color_palette("mycolormap", n_colors=10, desat=1)
    rank = np.random.choice([1, 3, 5, 6, 7, 8, 10], 200)  # test with 2, 4 and 9 missing
    y = np.random.uniform(0, 10, rank.shape)
    
    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 4))
    
    sns.pointplot(x=rank, y=y, hue=rank, palette=cpal, ax=ax1)
    ax1.set_title('without  hue_order')
    ax1.legend(bbox_to_anchor=(1.01, 1.05), loc='upper left')
    
    sns.pointplot(x=rank, y=y, hue=rank, hue_order=range(1, 11), palette=cpal, ax=ax2)
    ax2.set_title('using hue_order')
    ax2.legend(bbox_to_anchor=(1.01, 1.05), loc='upper left')
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2021-12-02
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 2017-01-20
    • 2018-02-06
    • 2016-02-20
    • 2011-10-28
    相关资源
    最近更新 更多