【问题标题】:heat map using matplotlib使用 matplotlib 的热图
【发布时间】:2014-05-07 21:05:25
【问题描述】:

我有一个这样生成的数据集:

 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,但我不知道该怎么做。

【问题讨论】:

标签: python matplotlib heatmap


【解决方案1】:

通常您会为此使用 imshowpcolormesh

例如:

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()

【讨论】:

  • @Jeo 我有一个疑问。如果我不知道我必须从数据文件本身中提取的 a 和 b 坐标,在这种情况下我们如何给出?假设我必须使用分布式城市的 gps 坐标进行数据集。
  • 为什么需要 ax.axis('tight')?谢谢:)
  • @tommy.carstensen - 默认情况下,matplotlib 将为轴限制选择“偶数”数。 (注意:这将在 2.0 中更改为 margins 样式填充。)ax.axis('tight') 指定轴限制应与数据限制完全匹配。在这种情况下,我们不想显示没有数据的区域,所以我们使用ax.axis('tight')
【解决方案2】:

我刚刚做了类似的事情,我使用了散点图。

plt.scatter(x_vals, y_vals, s = 100,  c = z_vals, cmap = 'rainbow')
c = plt.colorbar()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多