【问题标题】:Python heatmap plot colorbarPython 热图绘图颜色条
【发布时间】:2016-07-20 12:40:41
【问题描述】:

到目前为止,我正在制作一个看起来像这样的情节:

我正在使用以下代码:

import matplotlib.pyplot as plt
import numpy as np
column_labels = ['A','B']
row_labels = ['A','B']
data = np.random.rand(2,2)
print(type(data))
data = np.array([[1, 0.232], [0.119, 1]])
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

我想要得到的是这样的:

我可以在哪里看到颜色条以及它们上的单元格的值。我需要在我的代码中添加什么来获得这些?

谢谢

【问题讨论】:

标签: python matplotlib heatmap


【解决方案1】:

你研究过seaborn吗?

import seaborn as sns
data = np.random.rand(2,2)
sns.heatmap(data, annot=True,  linewidths=.5)

【讨论】:

  • 哈哈,它是一个很酷的库:stanford.edu/~mwaskom/software/seaborn/examples 您可以将 matplotlib 轴作为 arg 传递给它,并且仍然使用您的所有 matplotlib 函数,例如 ax.set_xticks() sns.heatmap(data, annot=True , 线宽=.5, ax = ax)
  • 如何在非ipython环境下运行?
  • 哦,明白了。将 matplotlib.pyplot 导入为 plt 。 plt.show()
【解决方案2】:

有关颜色条,请参阅this example。你猜对了,正确的函数调用就是ax.colorbar()

关于pcolor 图上的值,恐怕您必须使用ax.text()“手动”添加它们。计算并循环单元格中心值并调用text() 函数。您可以使用关键字参数horizontalalignment='center'verticalalignment='center' 使文本值以x, y 为中心。

【讨论】:

    猜你喜欢
    • 2019-03-08
    • 2021-01-11
    • 2018-06-03
    • 2015-11-07
    • 2020-12-26
    • 1970-01-01
    • 2021-09-28
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多