如何在 matplotlib 中根据 x、y、z 坐标绘制等高线图? (plt.contourf 或 plt.contour)

2024-03-28

These meshgrid对我来说使用起来有点混乱。我正在尝试用以下内容绘制散点图x and y坐标与覆盖在散点图上的等值线图,并具有连续分布z坐标。类似于高程图。

如果我使用meshgrid使用 x、y 和 z 坐标,然后我得到每个的 3D 数组,这仍然是不正确的输入。

df_xyz = pd.read_table("https://pastebin.com/raw/f87krHFK", sep="\t", index_col=0)
x = df_xyz.iloc[:,0].values
y = df_xyz.iloc[:,1].values
z = df_xyz.iloc[:,2].values

XX, YY = np.meshgrid(x,y)
with plt.style.context("seaborn-white"):
    fig, ax = plt.subplots(figsize=(13,8))
    ax.scatter(x,y, color="black", linewidth=1, edgecolor="ivory", s=50)
    ax.contourf(XX,YY,z)
#     TypeError: Input z must be a 2D array.

XX, YY, ZZ = np.meshgrid(x,y,z)
with plt.style.context("seaborn-white"):
    fig, ax = plt.subplots(figsize=(13,8))
    ax.scatter(x,y, color="black", linewidth=1, edgecolor="ivory", s=50)
    ax.contourf(XX,YY,ZZ)
#     TypeError: Input z must be a 2D array.

Here's my current output: enter image description here

I am trying to do something similar to this: enter image description here


import pandas as pd
import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
%matplotlib inline

df_xyz = pd.read_table("https://pastebin.com/raw/f87krHFK", sep="\t", index_col=0)
x = df_xyz.iloc[:,0].values
y = df_xyz.iloc[:,1].values
z = df_xyz.iloc[:,2].values

def plot_contour(x,y,z,resolution = 50,contour_method='linear'):
    resolution = str(resolution)+'j'
    X,Y = np.mgrid[min(x):max(x):complex(resolution),   min(y):max(y):complex(resolution)]
    points = [[a,b] for a,b in zip(x,y)]
    Z = griddata(points, z, (X, Y), method=contour_method)
    return X,Y,Z

X,Y,Z = plot_contour(x,y,z,resolution = 50,contour_method='linear')

with plt.style.context("seaborn-white"):
    fig, ax = plt.subplots(figsize=(13,8))
    ax.scatter(x,y, color="black", linewidth=1, edgecolor="ivory", s=50)
    ax.contourf(X,Y,Z)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 matplotlib 中根据 x、y、z 坐标绘制等高线图? (plt.contourf 或 plt.contour) 的相关文章

随机推荐