首页 > 解决方案 > 将 1-D x、y、z 向量转换为 2D 网格

问题描述

我有最初位于 3 列数据中的空间数据集 - x、y、z

请运行此代码并查看数据的外观。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

data = pd.DataFrame(np.array([[50. , 50. ,  0.3],
       [55. , 25. , -1.5],
       [ 6.6, 47.4,  0.1],
       [35. , 34.9,  1. ],
       [32.7, 56.3,  1.9]]), columns=['x', 'y', 'z'])

x = data['x']
y = data['y']
z = data['z']

def plot_sparse(x, y, z, ax, dist_max, **kwargs):

    assert len(x) == len(y) == len(z), "x, y, and z must have the same dimension"

    sc = ax.scatter(x, y, c=z, **kwargs)
    ax.set_aspect("equal")
    ax.set_xlim(0, dist_max)
    ax.set_ylim(0, dist_max)

    return sc

fig, ax = plt.subplots()
sc = plot_sparse(x, y, z, ax=ax, dist_max=80)
fig.colorbar(sc)

我想复制使用 meshgrid 生成的图形:

[X, Y] = np.meshgrid(x, y)

fig, ax = plt.subplots()
sc = ax.scatter(x, y)
ax.set_aspect("equal")
ax.set_xlim(0, 80)
ax.set_ylim(0, 80)

但我不知道如何将 z 轴的值嵌入网格中。上面使用 meshgrid 的代码在 2D 曲面图上不会有颜色条,但我想使用 meshgrid 数据类型制作颜色条。

我怎样才能做到这一点?

标签: pythonnumpymatplotlib2d

解决方案


推荐阅读