Python 如何将散点图转换为等高线图?

Python 如何将散点图转换为等高线图?,python,matplotlib,contour,Python,Matplotlib,Contour,我想把散点图转换成等高线图。我如何利用现有的数据来做这件事?代码如下: import numpy as np import matplotlib.pyplot as plt x = np.array([-75.55846, -75.5459 , -75.56686, -75.55276, -75.57951, -75.58955, -75.59967, -75.53964, -75.65485, -75.55292, -75.59622, -75.57392, -75.47077,

我想把散点图转换成等高线图。我如何利用现有的数据来做这件事?代码如下:

import numpy as np
import matplotlib.pyplot as plt
x = np.array([-75.55846, -75.5459 , -75.56686, -75.55276, -75.57951, -75.58955,
   -75.59967, -75.53964, -75.65485, -75.55292, -75.59622, -75.57392,
   -75.47077, -75.58644, -75.68264, -75.56732, -75.59502, -75.37198,
   -75.59585, -75.57081, -75.40989, -75.50928, -75.54841, -75.72734,
   -75.36676, -75.79303, -75.36966, -75.69282, -75.42498, -75.57986,
   -75.58644, -75.64551, -75.45509, -75.47098])
y = np.array([38.07759, 38.07541, 38.06712, 38.09973, 38.06692, 38.09264,
   38.08731, 38.0822 , 38.36981, 38.06027, 38.07962, 38.08531,
   37.93448, 38.07716, 37.71758, 38.08925, 38.0975 , 38.33174,
   38.05731, 38.05515, 38.0547 , 38.1398 , 38.066  , 38.27009,
   37.93415, 38.24889, 38.19691, 38.03272, 38.19954, 37.91286,
   37.97847, 38.29755, 38.01239, 37.93453])
z = np.array([17.526, 21.336, 19.558, 17.78 , 20.828, 20.828, 20.066, 21.082,
   18.542, 20.32 , 19.812, 19.05 , 16.51 , 20.066, 25.654, 16.51 ,
   18.542, 17.018, 20.828, 21.844, 21.59 , 16.764, 20.828, 19.558,
   19.812, 22.606, 25.146, 19.558, 20.574, 24.13 , 35.306, 19.558,
   23.876, 18.796])
fig, ax = plt.subplots(figsize=(8,8))
ax.scatter(x, y, c=z)
plt.show()

这不一定是最好的方法,但其中一种方法可能是将数据转换为x,y栅格中每个点的z值。这可以通过多种不同的方法实现,但我选择的方法是基于到每个点的距离使用z值的加权平均值。可以调整
衰减
,以更改点的影响随距离该点越远而改变的程度(保持其值为正值)


contourf
也可以使用。

我想我找到了一个解决方案——见下文。基本上,x、y和z是1D阵列,而x、y和z是轮廓接受并工作的2D阵列。我会说我确实环顾四周想弄清楚这件事,所以这不是我一个人干的

def grid(x, y, z, resX=100, resY=100):
    #prepare to create grid
    xi = np.linspace(min(x), max(x), resX)
    yi = np.linspace(min(y), max(y), resY)

    #grid x, y, z
    X, Y = np.meshgrid(xi, yi)
    Z = griddata((x, y), z, (X, Y), method='linear')
    return X, Y, Z
ax.tricontourf(x,y,z)
?尽管您的数据非常稀少。
def grid(x, y, z, resX=100, resY=100):
    #prepare to create grid
    xi = np.linspace(min(x), max(x), resX)
    yi = np.linspace(min(y), max(y), resY)

    #grid x, y, z
    X, Y = np.meshgrid(xi, yi)
    Z = griddata((x, y), z, (X, Y), method='linear')
    return X, Y, Z