只绘制热图的颜色条部分。

huangapple go评论113阅读模式
英文:

How can I plot just the colorbar of a heatmap?

问题

你可以只绘制色条而不绘制热力图本身,可以使用以下代码:

  1. import seaborn as sns
  2. import io
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. A = np.random.rand(100, 100)
  6. # 创建热力图但不显示
  7. g = sns.heatmap(A, cbar=False)
  8. # 单独绘制色条
  9. cbar = plt.colorbar(g.get_children()[0], ax=g, orientation='vertical')
  10. cbar.set_label('Colorbar Label')
  11. plt.show()
英文:

I would like to plot just the colorbar for a heatmap. Here is a MWE:

  1. import seaborn as sns
  2. import io
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. A = np.random.rand(100,100)
  6. g = sns.heatmap(A)
  7. plt.show()

How can I plot just its colorbar and not the heatmap itself?

答案1

得分: 3

尝试手动处理:

  1. import matplotlib as mpl
  2. import numpy as np
  3. fig, ax = plt.subplots(figsize=(1, 4))
  4. # vmin, vmax = np.nanmin(A), np.nanmax(A)
  5. cmap = mpl.colormaps['rocket']
  6. norm = mpl.colors.Normalize(0, 1) # 或者使用 vmin, vmax
  7. cbar = fig.colorbar(mpl.cm.ScalarMappable(norm, cmap), ax)
  8. plt.tight_layout()
  9. plt.show()

输出:

只绘制热图的颜色条部分。

英文:

Try to handle it manually:

  1. import matplotlib as mpl
  2. import numpy as np
  3. fig, ax = plt.subplots(figsize=(1, 4))
  4. # vmin, vmax = np.nanmin(A), np.nanmax(A)
  5. cmap = mpl.colormaps['rocket']
  6. norm = mpl.colors.Normalize(0, 1) # or vmin, vmax
  7. cbar = fig.colorbar(mpl.cm.ScalarMappable(norm, cmap), ax)
  8. plt.tight_layout()
  9. plt.show()

Output:

只绘制热图的颜色条部分。

答案2

得分: 0

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

  1. import seaborn as sns
  2. import matplotlib.pyplot as plt
  3. A = [[a] for a in range(100)] # 示例热力图
  4. fig, ax = plt.subplots()
  5. sns.heatmap(A, cbar=False, ax=ax)
  6. cax = fig.add_axes([1.0, 0.0, 0.0, 1.0]) # 调整位置和大小
  7. 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:

  1. import seaborn as sns
  2. import matplotlib.pyplot as plt
  3. A = [[a] for a in range(100)] # sample heatmap
  4. fig, ax = plt.subplots()
  5. sns.heatmap(A, cbar=False, ax=ax)
  6. cax = fig.add_axes([1.0, 0.0, 0.0, 1.0]) # Adjust the position and size
  7. plt.show()

只绘制热图的颜色条部分。

huangapple
  • 本文由 发表于 2023年6月8日 15:35:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76429590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定