如何使用python imshow,例如,处理不规则的数据点?

问题描述 投票:0回答:2

假设我有一个

(xi, yi, zi)
形式的数据点列表,并且我想用它绘制 2D 密度图。在mathematica中,你只需调用函数
ListDensityPlot
函数即可。在Python中,密度图似乎是通过使用
imshow
来实现的。然而,似乎所需的数据应该是常规形式。给定数据集如何得到类似的效果?

这是数学代码:

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)  # ???
python matplotlib plot wolfram-mathematica density-plot
2个回答
0
投票

您应该创建一个数据数组,例如这样:

import matplotlib.pyplot as plt
import numpy as np

def f(x, y):
    return x+y

N = 100
xs_raw = np.random.random(N)
ys_raw = np.random.random(N)
xs, ys = np.meshgrid(xs_raw, ys_raw) # make a coordinate array
zs = f(xs, ys) # make a 2D data array

fig = plt.figure()
ax = fig.add_subplot()
c = ax.imshow(zs, cmap='RdBu_r')
fig.colorbar(c, ax=ax)
plt.show()

输出:

或者,您可以简单地使用

zs = np.random.rand(100, 100)
生成该数据数组,如示例 here 中所示。


0
投票

我认为您正在寻找

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

© www.soinside.com 2019 - 2024. All rights reserved.