如何在不规则数据点上使用Python的imshow?
假设我有一组数据点,格式是 (xi, yi, zi)
,我想用这些数据画一个二维密度图。在 Mathematica 中,你只需要调用 ListDensityPlot
这个函数就可以了。而在 Python 中,似乎是通过 imshow
来实现密度图。不过,看起来需要的数据格式要比较规整。那么,给定这些数据集,怎么才能得到类似的效果呢?
这里是 Mathematica 的代码:
n = 100;
xs = RandomReal[1, n];
ys = RandomReal[1, n];
zs = xs + ys;
data = Table[{xs[[i]], ys[[i]], zs[[i]]}, {i, n}];
ListDensityPlot[data, PlotRange -> All, PlotLegends -> Automatic]
上面代码的效果是这样的(当然,你可以设置范围来去掉白色区域):
在 Python 中,我已经生成了数据,怎么把它放进 list_density_plot
函数里,达到类似的效果呢?
def f(x, y):
return x+y
N = 100
xs = np.random.random(N)
ys = np.random.random(N)
zs = f(xs, ys)
data = [(xs[i], ys[i], zs[i]) for i in range(N)]
list_density_plot(data) # ???
1 个回答
2
我觉得你可能在找 plt.tricontourf
或者 plt.tripcolor
。
下面是一个使用 plt.tripcolor
的例子:
import matplotlib.pyplot as plt
import numpy as np
def f(x, y):
return x + y
N = 100
xs = np.random.random(N)
ys = np.random.random(N)
zs = f(xs, ys)
plt.tripcolor(xs, ys, zs)
plt.show()