如何从值表中绘制等高线?

问题描述

我有一个包含 2 个特征 (x,y) 的表 - 以及一个长度相同的向量,其中包含它们对应的值 (z)

我正在尝试使用 matplotlib 将其打印为 2D 绘图,但出现错误

TypeError: Input z must be at least a (2,2) shaped array,but has shape (5797,1)

有什么办法可以解决这个问题吗? (因为我试图使用一维数组而不是二维数组)

相关代码

x,y = train_features[:,0],train_features[:,1]
z = train_predictions.detach()
print(x.size())
print(y.size())
print(z.size())

plt.figure()
CS = plt.contour(x,y,z)
CS = plt.contourf(x,z)
plt.clabel(CS,fontsize=8,colors='black')
cbar = plt.colorbar(CS)

打印命令产生的打印:

torch.Size([5797])
torch.Size([5797])
torch.Size([5797,1])

编辑: 我尝试用第二种方法来实现:

import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np

npts = 200
ngridx = 100
ngridy = 200
x = train_features[:,0]
y = train_features[:,1]
z = train_predictions.detach().squeeze()


fig,ax1 = plt.subplots()

# -----------------------
# Interpolation on a grid
# -----------------------
# A contour plot of irregularly spaced data coordinates
# via interpolation on a grid.

# Create grid values first.
xi = np.linspace(1,10,ngridx)
yi = np.linspace(1,ngridy)

# Perform linear interpolation of the data (x,y)
# on a grid defined by (xi,yi)
triang = tri.Triangulation(x,y)
interpolator = tri.LinearTriInterpolator(triang,z)
Xi,Yi = np.meshgrid(xi,yi)
zi = interpolator(Xi,Yi)

ax1.contour(xi,yi,zi,levels=100,linewidths=0.5,colors='k')
cntr1 = ax1.contourf(xi,levels=14,cmap="RdBu_r")

fig.colorbar(cntr1,ax=ax1)
ax1.plot(x,'ko',ms=3)
ax1.set_title('grid and contour (%d points,%d grid points)' %
              (npts,ngridx * ngridy))

但得到的图像如下:

enter image description here

即使 z 的值是:

tensor([-0.2434,-0.2155,-0.1900,...,64.7516,65.2064,65.6612])

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)