使用散点数据集在MatPlotLib中生成热图

4 投票
1 回答
8425 浏览
提问于 2025-04-16 19:47

我的问题几乎和这个问题一模一样。不过,我对那些回答不太满意,因为我想生成一个真正的热图,而不是明确地把数据分组。

具体来说,我想展示一个函数,这个函数是散点数据和一个自定义核(比如1/x^2)卷积的结果。

我应该如何用matplotlib来实现这个呢?

编辑:基本上,我做的就是这个。结果在这里。我想保留所有的内容,包括坐标轴、标题、标签等等。基本上就是想把图改成我描述的那样,同时尽量少重新实现其他部分。

1 个回答

13

首先,使用matplotlib.dats.date2num这个工具,把你的时间序列数据转换成数字格式。接着,画一个矩形网格,覆盖你想要的x轴和y轴范围,然后在这个图上进行卷积操作。最后,制作一个伪彩色图,展示你的卷积结果,并把x轴的标签格式调整成日期。

标签的格式可能有点复杂,但总体上还是有一些不错的文档说明。你只需要把AutoDateFormatter替换成DateFormatter,并使用合适的格式字符串就可以了。

你可能还需要根据你的数据调整卷积中的常数。

import numpy as np
import datetime as dt
import pylab as plt
import matplotlib.dates as dates

t0 = dt.date.today()
t1 = t0+dt.timedelta(days=10)

times = np.linspace(dates.date2num(t0), dates.date2num(t1), 10)
dt = times[-1]-times[0]
price =  100 - (times-times.mean())**2
dp = price.max() - price.min()
volume = np.linspace(1, 100, 10)

tgrid = np.linspace(times.min(), times.max(), 100)
pgrid = np.linspace(70, 110, 100)
tgrid, pgrid = np.meshgrid(tgrid, pgrid)
heat = np.zeros_like(tgrid)

for t,p,v in zip(times, price, volume):
    delt = (t-tgrid)**2
    delp = (p-pgrid)**2
    heat += v/( delt + delp*1.e-2 + 5.e-1 )**2

fig = plt.figure()
ax = fig.add_subplot(111)
ax.pcolormesh(tgrid, pgrid, heat, cmap='gist_heat_r')

plt.scatter(times, price, volume, marker='x')

locator = dates.DayLocator()
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(dates.AutoDateFormatter(locator))
fig.autofmt_xdate()

plt.show()

脚本输出

撰写回答