简体   繁体   中英

How to replace lineplot legend with a colorbar

When I run the following code, I get a plot:

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

在此处输入图像描述

But when I try replacing the legend with a colorbar, the colorbar incorrectly inverts the colors!


    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()

在此处输入图像描述

Why is the colorbar flipped and how do I stop this?

You could explicitly set a colormap for the ScalarMappable as well as for the lineplot . That way both use the same:

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()

带有色调和颜色条的 sns.lineplot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM