matplotlib 如何仅绘制热图的颜色条?[副本]

ncecgwcz  于 2023-06-23  发布在  其他
关注(0)|答案(2)|浏览(131)

此问题已在此处有答案

Standalone colorbar(6个答案)
14天前关闭
我想只绘制热图的颜色条。下面是一个MWE:

import seaborn as sns
import io
import matplotlib.pyplot as plt
import numpy as np

A = np.random.rand(100,100)

g = sns.heatmap(A)
plt.show()

我如何绘制它的颜色条而不是热图本身?

esyap4oy

esyap4oy1#

尝试手动处理:

import matplotlib as mpl
import numpy as np

fig, ax = plt.subplots(figsize=(1, 4))
# vmin, vmax =  np.nanmin(A), np.nanmax(A)
cmap = mpl.colormaps['rocket']
norm = mpl.colors.Normalize(0, 1)  # or vmin, vmax
cbar = fig.colorbar(mpl.cm.ScalarMappable(norm, cmap), ax)
plt.tight_layout()
plt.show()

输出:

wecizke3

wecizke32#

据我所知,仅绘制颜色条是不可能的。要查看颜色条的整个光谱,您可以使用范围从0到100的示例热图:

import seaborn as sns
import matplotlib.pyplot as plt

A = [[a] for a in range(100)] # sample heatmap

fig, ax = plt.subplots()

sns.heatmap(A, cbar=False, ax=ax)

cax = fig.add_axes([1.0, 0.0, 0.0, 1.0])  # Adjust the position and size

plt.show()

相关问题