使用matplotlib的热图 [英] heat map using matplotlib
本文介绍了使用matplotlib的热图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个以这种方式生成的数据集:
I have a dataset generated in this way:
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)的颜色. 我需要它来分析局部最小值.
I would like and head map where z define the color in the point (a,b) . I need this to analyze local minimum.
我正在使用matplotlib,但我不知道该如何继续.
I am using matplotlib but I do not know exactly how to proceed.
推荐答案
通常,您将为此使用imshow
或pcolormesh
.
Typically you'd use imshow
or pcolormesh
for this.
例如:
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()
但是,最好将示例代码编写为:
However, it would be better to write your example code as:
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()
这篇关于使用matplotlib的热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文