【问题标题】:How to do a contour plot from x,y,z coordinates in matplotlib? (plt.contourf or plt.contour)如何从 matplotlib 中的 x、y、z 坐标绘制等高线图? (plt.contourf 或 plt.contour)
【发布时间】:2019-03-26 20:53:57
【问题描述】:

这些meshgrid 对我来说有点令人困惑。我正在尝试使用xy 坐标绘制散点图,等高线图覆盖在散点上,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.

这是我当前的输出:

我正在尝试做类似的事情:

【问题讨论】:

  • 你可以只使用tricontourf然后分散在上面

标签: python numpy matplotlib contour topology


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多