[英]python xyz data transformation for surface plot
I want to plot a 3D surface in matplotlib from xy and z data.我想从 xy 和 z 数据在 matplotlib 中绘制 3D 表面。 For this I need to do a seemingly simple data transformation but I am unsure on how to proceed.为此,我需要做一个看似简单的数据转换,但我不确定如何进行。
My x and y data are uniform integers because it will be the surface of an image.我的 x 和 y 数据是统一整数,因为它将是图像的表面。 My data is present in the form of a 512x512 numpy array.我的数据以 512x512 numpy 数组的形式存在。 The values of the array are the z values, and the indexes are the x and y values respectively.数组的值是 z 值,索引分别是 x 和 y 值。
So if arr
is my array, arr[x, y]
would give my z
.所以如果arr
是我的数组, arr[x, y]
会给我的z
。 The form just looks like this:表格看起来像这样:
z z z z ... z (512 columns)
z z z z ... z
z z z z ... z
z z z z ... z
. . . .
. . . .
z z z z (512 rows)
How do I get my data in the form of three columns x, y, z so I can do the surface plot?如何以三列 x、y、z 的形式获取数据,以便绘制曲面图? It should look like this after the transform:转换后应该是这样的:
x | y | z
---------
0 | 0 | z
1 | 0 | z
2 | 0 | z
. | . | .
. | . | .
511 | 0 | z
0 | 1 | z
1 | 1 | z
2 | 1 | z
. | . | .
. | . | .
I tried to work with np.meshgrid
and np.flatten
but can't get it to work the way I want.我尝试使用np.meshgrid
和np.flatten
但无法按照我想要的方式工作。 Maybe theres an even easier pandas solution to this.也许有一个更简单的熊猫解决方案。 Or maybe I can even plot it with the original form of the data?或者我什至可以用数据的原始形式绘制它?
Any suggestion is appreciated :)任何建议表示赞赏:)
You would use np.meshgrid
like this:你会像这样使用np.meshgrid
:
# Make coordinate grids
x, y = np.meshgrid(np.arange(arr.shape[0]), np.arange(arr.shape[1]), indexing='ij')
# Flatten grid and data and stack them into a single array
data = np.stack([x.ravel(), y.ravel(), arr.ravel()], axis=1)
For example:例如:
import numpy as np
arr = np.arange(12).reshape((3, 4))
x, y = np.meshgrid(np.arange(arr.shape[0]), np.arange(arr.shape[1]), indexing='ij')
data = np.stack([x.ravel(), y.ravel(), arr.ravel()], axis=1)
print(data)
Output:输出:
[[ 0 0 0]
[ 0 1 1]
[ 0 2 2]
[ 0 3 3]
[ 1 0 4]
[ 1 1 5]
[ 1 2 6]
[ 1 3 7]
[ 2 0 8]
[ 2 1 9]
[ 2 2 10]
[ 2 3 11]]
EDIT:编辑:
Actually, if you want to have your final array such that x
values increase first (as in the example you gave), you could do it like this:实际上,如果你想让你的最终数组首先增加x
值(如你给出的例子),你可以这样做:
x, y = np.meshgrid(np.arange(arr.shape[0]), np.arange(arr.shape[1]), indexing='xy')
data = np.stack([x.ravel(), y.ravel(), arr.T.ravel()], axis=1)
In this case you would get:在这种情况下,您将获得:
[[ 0 0 0]
[ 1 0 4]
[ 2 0 8]
[ 0 1 1]
[ 1 1 5]
[ 2 1 9]
[ 0 2 2]
[ 1 2 6]
[ 2 2 10]
[ 0 3 3]
[ 1 3 7]
[ 2 3 11]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.