【问题标题】:How to replace lineplot legend with a colorbar如何用颜色条替换线图图例
【发布时间】:2022-01-25 07:43:58
【问题描述】:

当我运行以下代码时,我得到了一个情节:

    tmp = sns.lineplot(
        data=inf_algs_results_df,
        x='alpha',
        y='runtime',
        hue='beta_rounded',
    )

但是当我尝试用颜色条替换图例时,颜色条会错误地反转颜色!


    tmp = sns.lineplot(
        data=inf_algs_results_df,
        x='alpha',
        y='runtime',
        hue='beta_rounded',
    )
    tmp.figure.colorbar(
        mpl.cm.ScalarMappable(
            norm=mpl.colors.Normalize(vmin=inf_algs_results_df['beta_rounded'].min(),
                                      vmax=inf_algs_results_df['beta_rounded'].max(),
                                      clip=False)),
        label=r'$\beta$')
    plt.show()

为什么颜色条会翻转,我该如何停止?

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    您可以为ScalarMappablelineplot 显式设置颜色图。这样两者都使用相同的:

    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    alpha_range = np.arange(8)
    beta_range = np.arange(11)
    df = pd.DataFrame({'alpha': np.tile(alpha_range, len(beta_range)),
                       'runtime': np.random.rand(len(alpha_range), len(beta_range)).cumsum(axis=0).ravel(),
                       'beta': np.repeat(beta_range, len(alpha_range))})
    cmap = plt.get_cmap('rocket_r')
    ax = sns.lineplot(data=df,
                      x='alpha',
                      y='runtime',
                      hue='beta',
                      palette=cmap)
    cbar = ax.figure.colorbar(mpl.cm.ScalarMappable(norm=mpl.colors.Normalize(vmin=df['beta'].min(),
                                                                              vmax=df['beta'].max(),
                                                                              clip=False),
                                                    cmap=cmap),
                              ticks=np.arange(df['beta'].min(), df['beta'].max() + 1),
                              label=r'$\beta$')
    # cbar.ax.invert_yaxis()  # optionally invert the yaxis of the colorbar
    # ax.legend_.remove()  # for testing purposes don't yet remove the legend
    plt.tight_layout()
    plt.show()
    

    【讨论】:

    • 是的!这似乎可以解决问题:)
    猜你喜欢
    • 2013-09-07
    • 1970-01-01
    • 2022-11-07
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2012-06-13
    • 1970-01-01
    相关资源
    最近更新 更多