How to replace lineplot legend with a colorbar(如何用颜色条替换线条图例)
本文介绍了如何用颜色条替换线条图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我运行以下代码时,我得到一个图:
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'$eta$')
plt.show()
为什么翻转颜色栏,以及如何停止此操作?
推荐答案
您可以显式设置ScalarMappable和lineplot的色彩映射表。这样两者使用相同:
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'$eta$')
# 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()
这篇关于如何用颜色条替换线条图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:如何用颜色条替换线条图例
基础教程推荐
猜你喜欢
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
