英文:
How can I plot just the colorbar of a heatmap?
问题
你可以只绘制色条而不绘制热力图本身,可以使用以下代码:
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, cbar=False)
# 单独绘制色条
cbar = plt.colorbar(g.get_children()[0], ax=g, orientation='vertical')
cbar.set_label('Colorbar Label')
plt.show()
英文:
I would like to plot just the colorbar for a heatmap. Here is a 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()
How can I plot just its colorbar and not the heatmap itself?
答案1
得分: 3
尝试手动处理:
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) # 或者使用 vmin, vmax
cbar = fig.colorbar(mpl.cm.ScalarMappable(norm, cmap), ax)
plt.tight_layout()
plt.show()
输出:
英文:
Try to handle it manually:
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()
Output:
答案2
得分: 0
仅绘制色条据我所知是不可能的。要查看整个色条的光谱,您可以使用一个仅从0到100的示例热力图:
import seaborn as sns
import matplotlib.pyplot as plt
A = [[a] for a in range(100)] # 示例热力图
fig, ax = plt.subplots()
sns.heatmap(A, cbar=False, ax=ax)
cax = fig.add_axes([1.0, 0.0, 0.0, 1.0]) # 调整位置和大小
plt.show()
英文:
Plotting just the colorbar is not possible to my knowledge. To see the whole spectrum of the colorbar, you could use a sample heatmap that is just a range from 0 to 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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论