Issue
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?
Solution
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()
Answered By - JohanC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.