【问题标题】:How to assign a value from an array to an (x,y)-point如何将数组中的值分配给(x,y)点
【发布时间】:2014-03-17 15:56:48
【问题描述】:

我有 3600 个 x 值和 3600 个 y 值。和一个数组(180x20)。我需要将其绘制为轮廓图并将第一个 x 值和第一个 y 值分配给第一个数组值 (A[0,0]) 等等...我该怎么做?

我的想法:

x,y = np.meshgrid(x,y)
plt.contourf(x,y,A)

不起作用:TypeError: Shape of x does not match that of z: found (3600, 3600) instead of (180, 20).我理解错误,但不知道如何解决。

【问题讨论】:

  • 听起来您原来的xy(在调用meshgrid 之前)只是规则网格上的“扁平化”二维坐标数组(与您的A 匹配)。如果是这样,您只需要x = x.reshape(180, 20)(y 也是如此)。
  • x 和 y 是列表。每个都有 3600 个值。如果我在网格网格之前使用 reshape 尝试它,则会出现此错误:AttributeError: 'list' object has no attribute 'reshape'。如果我在 meshgrid 之后使用它,则会出现:ValueError: total size of new array must be unchanged
  • 如果它们是列表,您需要将它们转换为数组。试试np.array(x).reshape(180,20)np.reshape(x, (180,20))

标签: python arrays matplotlib


【解决方案1】:

我认为您对 meshgrid 的作用有些困惑。听起来你只是想要reshape

numpy.meshgrid的解释

作为 meshgrid 的示例,假设我们有一个 5x5 的“z”值网格:

import numpy as np
z = np.random.random((5,5))

我们有一行的 x 坐标和一列的 y 坐标:

ny, nx = z.shape
x = np.linspace(5, 7, nx)
y = np.linspace(-2, 8, ny)

print '-----Z-----\n', z, '\n'
print '-----X-----\n', x, '\n'
print '-----Y-----\n', y, '\n'

所以,在这一点上,我们有:

-----Z-----
[[ 0.70319561  0.0141277   0.17580355  0.20411183  0.81714624]
 [ 0.45093838  0.18241847  0.27477369  0.4881957   0.62157783]
 [ 0.83172549  0.75278372  0.64856436  0.76651935  0.0152465 ]
 [ 0.50908933  0.51557264  0.9975723   0.39579782  0.71333262]
 [ 0.58998339  0.59205064  0.42716255  0.14138964  0.38212301]]

-----X-----
[ 5.   5.5  6.   6.5  7. ]

-----Y-----
[-2.   0.5  3.   5.5  8. ]

numpy.meshgrid 的意思是将这些一维数组的列和行坐标转换为与z 形状匹配的二维数组:

yy, xx = np.meshgrid(y, x)

print '-----XX----\n', xx, '\n'
print '-----YY----\n', yy, '\n'

这会产生:

-----XX----
[[ 5.   5.   5.   5.   5. ]
 [ 5.5  5.5  5.5  5.5  5.5]
 [ 6.   6.   6.   6.   6. ]
 [ 6.5  6.5  6.5  6.5  6.5]
 [ 7.   7.   7.   7.   7. ]]

-----YY----
[[-2.   0.5  3.   5.5  8. ]
 [-2.   0.5  3.   5.5  8. ]
 [-2.   0.5  3.   5.5  8. ]
 [-2.   0.5  3.   5.5  8. ]
 [-2.   0.5  3.   5.5  8. ]]

使用您拥有的数据

如果我的理解正确,您的 x 和 y 数组都是 3600 个元素的列表,而您的 z 数组是 180x20。 (注意180 * 20 == 3600)因此,我认为你拥有的数据相当于在做:

yourx, youry = xx.flatten().tolist(), yy.flatten().tolist()

显然,您的数据要大得多,但如果我们扩展上面的示例,它看起来像:

---yourx---
[5.0, 5.0, 5.0, 5.0, 5.0, 5.5, 5.5, 5.5, 5.5, 5.5, 6.0, 6.0, 6.0, 6.0, 6.0, 6.5, 6.5, 6.5, 6.5, 6.5, 7.0, 7.0, 7.0, 7.0, 7.0]

---youry---
[-2.0, 0.5, 3.0, 5.5, 8.0, -2.0, 0.5, 3.0, 5.5, 8.0, -2.0, 0.5, 3.0, 5.5, 8.0, -2.0, 0.5, 3.0, 5.5, 8.0, -2.0, 0.5, 3.0, 5.5, 8.0]

因此,您只想将列表重塑为与z 形状相同的二维数组。例如:

print np.reshape(yourx, z.shape)

产量

[[ 5.   5.   5.   5.   5. ]
 [ 5.5  5.5  5.5  5.5  5.5]
 [ 6.   6.   6.   6.   6. ]
 [ 6.5  6.5  6.5  6.5  6.5]
 [ 7.   7.   7.   7.   7. ]]

换句话说,你想要:

plt.contourf(np.reshape(yourx, z.shape), np.reshape(youry, z.shape), z)

【讨论】:

    猜你喜欢
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 2011-09-28
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    相关资源
    最近更新 更多