import matplotlib.pyplot as plt
import numpy as np
import random
x = np.random.randint(-100,100,1000)
y = np.random.randint(-100,100,1000)
size = np.random.rand(100) * 100
mask1 = abs(x) > 50
mask2 = abs(y) > 50
x = x[mask1 mask2]
y = y[mask1 mask2]
plt.scatter(x, y, s=size, c=x, cmap='jet', alpha=0.7)
plt.colorbar()
plt.show()
ValueError Traceback (most recent call last)
Input In [56], in <cell line: 16>()
12 x = x[mask1 mask2]
13 y = y[mask1 mask2]
---> 16 plt.scatter(x, y, s=size, c=x, cmap='jet', alpha=0.7)
17 plt.colorbar()
18 plt.show()
ValueError: s must be a scalar, or float array-like with the same size as x and y
I can't find what's wrong with this code. It just returns a ValueError. I am assuming something is wrong with the 'size = ' part. I tried changing size = np.random.rand(100) to (1000) but still didn't work.
CodePudding user response:
The problem lies within s=size
. Either s
has to be a single value for all your data points or there has to be a value for every data point. But x.shape
and y.shape
will be random. So in order to give every point a different size:
x = np.random.randint(-100,100,1000)
y = np.random.randint(-100,100,1000)
mask1 = abs(x) > 50
mask2 = abs(y) > 50
x = x[mask1 mask2]
y = y[mask1 mask2]
size = np.random.rand(x.shape[0]) * 100 # choose size depending on the number of data points x
plt.scatter(x, y, s=size, c=x, cmap='jet', alpha=0.7)
plt.colorbar()
plt.show()
I tested it and it works fine, and hopefully as you expect.
CodePudding user response:
According to official documentation of scatter, size attribute should be a scalar or float array-like with the same size as x and y. After you modified your x and y variables, size variable shape doesn't match with x or y. That's why it's throwing value error.