使用matplotlib绘制热图
我有一个这样生成的数据集:
aa = linspace(A - 5, A + 5, n_points)
bb = linspace(B - 1.5, B + 1.5, n_points)
z = []
for a in aa:
for b in bb:
z.append(cost([a, b]))
我想要一个热图,其中 z 值决定了点 (a,b) 的颜色。 我需要这个图来分析局部最小值。
我正在使用 matplotlib,但我不太清楚该怎么做。
2 个回答
-1
我刚刚做了类似的事情,我使用了散点图。
plt.scatter(x_vals, y_vals, s = 100, c = z_vals, cmap = 'rainbow')
c = plt.colorbar()
5
通常情况下,你会使用 imshow
或 pcolormesh
来实现这个功能。
比如说:
import numpy as np
import matplotlib.pyplot as plt
n_points = 10
aa = np.linspace(-5, 5, n_points)
bb = np.linspace(-1.5, 1.5, n_points)
def cost(a, b):
return a + b
z = []
for a in aa:
for b in bb:
z.append(cost(a, b))
z = np.reshape(z, [len(aa), len(bb)])
fig, ax = plt.subplots()
im = ax.pcolormesh(aa, bb, z)
fig.colorbar(im)
ax.axis('tight')
plt.show()
不过,把你的示例代码写得更好一些是这样的:
import numpy as np
import matplotlib.pyplot as plt
n_points = 10
a = np.linspace(-5, 5, n_points)
b = np.linspace(-1.5, 1.5, n_points)
a, b = np.meshgrid(b, a)
z = a + b # Vectorize your cost function
fig, ax = plt.subplots()
im = ax.pcolormesh(a, b, z)
fig.colorbar(im)
ax.axis('tight')
plt.show()
或者,甚至可以更简洁一些:
import numpy as np
import matplotlib.pyplot as plt
npoints = 10
b, a = np.mgrid[-5:5:npoints*1j, -1.5:1.5:npoints*1j]
z = a + b
fig, ax = plt.subplots()
im = ax.pcolormesh(a, b, z)
fig.colorbar(im)
ax.axis('tight')
plt.show()