Home > Enterprise >  How to replace lineplot legend with a colorbar
How to replace lineplot legend with a colorbar

Time:01-25

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',
    )

enter image description here

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

enter image description here

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

CodePudding user response:

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 with hue and colorbar

  •  Tags:  
  • Related