代码之家  ›  专栏  ›  技术社区  ›  O.rka

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

  •  0
  • O.rka  · 技术社区  · 6 年前

    这些 meshgrid 对我来说有点困惑。我想用 x y 覆盖在散点图上的等高线图坐标 z 协调。类似于立面图。

    如果我用 网格 使用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.
    

    这是我的电流输出: enter image description here

    我正试图做类似的事情: enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   user10140465    6 年前
    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)