Reputation: 163
I have fallowing problem:
I have a list of arrays with x, y points, e.g. 100 arrays with a shape of (400, 2) (or just array of shape (100, 400, 2)
), where the last dimension corresponds to the x, y coordinates. I would like to colour the every array with a different colour from a colour gradient, like the plot below:
So points that corresponds to the 0, 1, 2 ... 10 have colours from violet to blue, from the 10 to the 100 are green to yellow etc.
I tried with the code below:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib as mpl
import numpy as np
N = 100
my_cord = np.stack([np.random.randn(400, 2) + np.random.randn(1, 2)*10 for j in range(N)])
fig, ax = plt.subplots()
cmap = plt.get_cmap('spring', N)
for i in range(N):
x, y = my_cord[i].T
cf = ax.scatter(x, y, cmap=cmap(i))
norm = mpl.colors.Normalize(vmin=0,vmax=N)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
plt.colorbar(sm)
ax.set_xlabel('IC 1')
ax.set_ylabel('IC 2')
fig.tight_layout()
plt.show()
but I'm getting different scatterplot colours than defined in the cmap:
Upvotes: 1
Views: 1346
Reputation: 80459
As your colorbar is logarithmic, it makes sense to use a LogNorm
. The size of the dots can be made smaller. For very small dots, the outline should be removed (e.g. setting ec='none'
).
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
N = 100
my_cord = np.stack([np.random.randn(400, 2) + np.random.randn(1, 2) * 10 for j in range(N)])
fig, ax = plt.subplots()
cmap = plt.get_cmap('spring', N)
norm = mpl.colors.LogNorm(vmin=1, vmax=N + 1)
for i in range(N):
cf = ax.scatter(my_cord[i, :, 0], my_cord[i, :, 1], color=cmap(norm(i + 1)), ec='none', marker=',', s=1)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
plt.colorbar(sm)
ax.set_xlabel('IC 1')
ax.set_ylabel('IC 2')
fig.tight_layout()
plt.show()
PS: The plot can also be created in one go by using the index as c=
and directly passing the cmap
:
norm = mpl.colors.LogNorm(vmin=1, vmax=N + 1)
cf = ax.scatter(my_cord[:, :, 0], my_cord[:, :, 1],
c=np.repeat(np.arange(1, N + 1), my_cord.shape[1]),
cmap='spring', ec='none', marker=',', s=1)
plt.colorbar(cf)
Upvotes: 1
Reputation: 35230
If you want to set the discrete colors here, you will need to modify the following.
cmap = plt.get_cmap('spring', N)
for i in range(N):
x, y = my_cord[i].T
cf = ax.scatter(x, y, color=cmap(i))
Upvotes: 1