Reputation: 4896
The matplotlib documentation explain in detail how to normalize colormaps for a pcolormesh, but how can I correctly do it for a scatter plot?
normalize = mcolors.Normalize(vmin=-1, vmax=1)
plt.scatter(x,y,z,cmap=colormap(normalize),marker='*',s=5)
doesn't work (TypeError: Cannot cast array data from dtype('O') to dtype('int64') according to the rule 'safe'
)
it's just that the z data are not exactly from -1 to 1, I am plotting multiple datasets that have the limits around +/- 0.93 - 98, but I want the colours to be centered at zero and go from -1 to 1 so that I have the same reference for all the various datasets.
Oh, and when I don't attempt to normalize, I get TypeError: scatter() got multiple values for keyword argument 's'
. Clearly I don't know how to use colormap in scatter plots.
Upvotes: 10
Views: 34781
Reputation: 2782
# define the range of values in the data (100 is arbitrary)
my_range = np.linspace(-1,1,100)
# cmap is a function. It returns (rgba) colors base on a range 0-1. Therefore,
# transform your values to 0-1 to use them as input for cmap()
cmap = cm.get_cmap('viridis', 100)
my_transformed_range = (my_range - np.min(my_range)) / (np.max(my_range) - np.min(my_range))
# colors should be supplied as a single color or a list (here using the cmap fx)
plt.scatter(my_range, np.ones(100), color=[cmap(i) for i in my_transformed_range])
Upvotes: 0
Reputation: 339550
The syntax you're using is completely different to the one in the linked documentation. There is essentially no difference between normalizing a scatter or a pcolor(mesh) or just any other scalar mappable object.
It's always
colormap = plt.cm.bwr #or any other colormap
normalize = matplotlib.colors.Normalize(vmin=-1, vmax=1)
plt.scatter(x, y, c=z, s=5, cmap=colormap, norm=normalize, marker='*')
Upvotes: 28