使用Matplotlib,我想绘制一个2D热图。我的数据是一个n × n的Numpy数组,每个数组的值都在0到1之间。对于这个数组的(i, j)元素,我想在热图的(i, j)坐标处画一个正方形,它的颜色与数组中元素的值成比例。
我该怎么做呢?
使用Matplotlib,我想绘制一个2D热图。我的数据是一个n × n的Numpy数组,每个数组的值都在0到1之间。对于这个数组的(i, j)元素,我想在热图的(i, j)坐标处画一个正方形,它的颜色与数组中元素的值成比例。
我该怎么做呢?
当前回答
带有参数interpolation='nearest'和cmap='hot'的imshow()函数应该能满足你的需要。
请查看插值参数细节,并参见imshow和图像反锯齿插值。
import matplotlib.pyplot as plt
import numpy as np
a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()
其他回答
我将使用matplotlib的pcolor/pcolormesh函数,因为它允许不均匀的数据间距。
示例来自matplotlib:
import matplotlib.pyplot as plt
import numpy as np
# generate 2 2d grids for the x & y bounds
y, x = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100))
z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
z = z[:-1, :-1]
z_min, z_max = -np.abs(z).max(), np.abs(z).max()
fig, ax = plt.subplots()
c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('pcolormesh')
# set the limits of the plot to the limits of the data
ax.axis([x.min(), x.max(), y.min(), y.max()])
fig.colorbar(c, ax=ax)
plt.show()
带有参数interpolation='nearest'和cmap='hot'的imshow()函数应该能满足你的需要。
请查看插值参数细节,并参见imshow和图像反锯齿插值。
import matplotlib.pyplot as plt
import numpy as np
a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()
使用matshow(),它是imshow的包装器,可以为显示矩阵设置有用的默认值。
a = np.diag(range(15))
plt.matshow(a)
https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.matshow.html
这只是一个包装了imshow的方便函数,用于设置显示矩阵的有用默认值。特别是: 设置原点=‘上’。 设置插值=“最近”。 设置方面=“=”。 蜱被放置在左边和上面。 刻度被格式化以显示整数索引。
对于2d numpy数组,简单地使用imshow()可能会帮助您:
import matplotlib.pyplot as plt
import numpy as np
def heatmap2d(arr: np.ndarray):
plt.imshow(arr, cmap='viridis')
plt.colorbar()
plt.show()
test_array = np.arange(100 * 100).reshape(100, 100)
heatmap2d(test_array)
这段代码生成一个连续的热图。
您可以从这里选择另一个内置的颜色地图。