user308827
user308827

Reputation: 21961

Scatter plot of 2 numpy 2-D arrays

I have 2 numpy 2D arrays

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

I want to show a scatter plot with x-axis values from arr1 and y-axis values from arr2. I tried this:

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

But I get this error:

ValueError: too many values to unpack (expected 2)

How to fix this?

Upvotes: 2

Views: 4098

Answers (1)

sacuL
sacuL

Reputation: 51335

IIUC, you don't need the zip step:

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

Or, you get the same by just plotting arr1 and arr2:

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

enter image description here

The reason being that by zipping, you are creating lots of coordinate tuples:

>>> 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)]

Which are correct (although they can't be packaged into 2 variables, because it is 16 coordinate pairs), but then you would basically want to iterate through to plot them, which is not ideal. Or you could re-zip them, but I think this is not an efficient way to do it:

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

Upvotes: 3

Related Questions