首页 > 解决方案 > 在 3D 曲面图中绘制 DataFrame

问题描述

我有一个数据框(大小:1008,100)。单元格的值在 0.1 和 1 之间。我想在曲面图中将其可视化,但我无法真正弄清楚 x、y 和 z 值将是什么。我想定位曲面图,如行(1008)与 x 轴对齐,列(100)与 y 轴对齐。任何帮助深表感谢。谢谢

标签: pythonmatplotlibdata-visualization

解决方案


您正在寻找的xy可以使用meshgrid创建。一个好的开始方法是在matplotlib 库中找到一个示例并从那里进行更改。举个例子:

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# create a data frame with 1008x100 values between 0.1 and 1.0
xs = np.arange(0, 1008)
ys = np.arange(0,100)
zs = np.square(xs[:, np.newaxis]) * np.square(ys[np.newaxis, :])
max_value = np.max(zs)
min_value = np.min(zs)
zs = (zs - min_value) / (max_value - min_value) * 0.9 + 0.1

data = pd.DataFrame(zs)

# create X and Y with np.meshgrid and the 2D data frame
#  (reusing the scratch variable xs and ys)
xs = np.arange(data.shape[0])   # [0,1,....,1007]
ys = np.arange(data.shape[1])   # [0,1,...,99]

X, Y = np.meshgrid(xs, ys)

# create a surface plot
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, data.T)

(注意:我需要转置datawith .T,不知道为什么,有时需要...)


推荐阅读