2个Numpy二维数组的散点图

时间:2018-11-29 16:51:57

标签: python numpy

我有2个numpy二维数组

import numpy as np
arr1 = np.random.rand(4,4)
arr2 = np.random.rand(4, 4)

我想显示一个散点图,其中x轴值来自arr1,y轴值来自arr2。我尝试过:

s = (arr1.ravel(), arr2.ravel())
x, y = zip(*s)
plt.scatter(x, y)

但是我得到这个错误:

ValueError: too many values to unpack (expected 2)

该如何解决?

1 个答案:

答案 0 :(得分:2)

IIUC,您不需要执行zip步骤:

s = (arr1.ravel(), arr2.ravel())
plt.scatter(*s)
plt.show()

或者,只需绘制arr1arr2即可得到相同的结果:

plt.scatter(arr1, arr2)
plt.show()

enter image description here

原因是通过压缩,您正在创建许多坐标元组:

>>> list(zip(*s))
[(0.5233576831070681, 0.3622905772322086), (0.6771459051981418, 0.46550530512072197), (0.5836238435117137, 0.9678582465614765), (0.5215640961420361, 0.05930220671158393), (0.0671420867491811, 0.3229294577997751), (0.09453539420217905, 0.5853394743453684), (0.14945382971858256, 0.7100764985571005), (0.6097216935812977, 0.008285702808878748), (0.8008615396938863, 0.8564656781773946), (0.0012100717276920525, 0.03915037044723313), (0.5749921053520953, 0.43147487440006294), (0.5965950855156836, 0.6485170240649151), (0.00223226469849902, 0.3134990067863225), (0.6424325871844799, 0.4041957463865189), (0.06797409254523168, 0.685192515451394), (0.9485129458199039, 0.6873427463294267)]

这是正确的(尽管不能将它们打包成2个变量,因为它是16个坐标对),但是您基本上希望迭代遍历以绘制它们,这是不理想的。或者,您可以重新压缩它们,但我认为这不是一种有效的方法:

x,y = zip(*zip(*s))
plt.scatter(x,y)
plt.show()