Roberto Landi
Roberto Landi

Reputation: 127

How to bind a colormap to an array?

I would like to get an array of colors starting from an array values.

for example:

a = [4,3,2,5,6,20,1,34]

I expect to had a new array with color like a viridis cmap of matplotlib, where the small numbers are binded (same index) with dark colors and the big numbers with light color.

Upvotes: 3

Views: 2040

Answers (2)

Michi Gruber
Michi Gruber

Reputation: 254

You could simply make an array with rgb colours in it like this:

colors = ["rgb(0, 0, 0)"]

And each possible number could have an entry in the array. So the number zero in this example would return the rgb for black.

Upvotes: 1

yatu
yatu

Reputation: 88236

You can use matplotlib.pyplot.Normalize so the data is normalized to the [0-1] interval when fed to the plot function. Here is an example of what it would look like, using the normalized ranges

a = [4,3,2,5,6,20,1,34]
# An example colormap
colormap = plt.cm.cool 
# Normalize using the min and max values in a
normalize = plt.Normalize(vmin=min(a), vmax=max(a))
# scatter plot with the parameters defined above
plt.scatter(range(len(a)), y=a, c=a, cmap=colormap, marker='o')

enter image description here

Note that you will have to use a as the c argument in matplotlib.pyplot.scatter, which as mentioned in the docs accepts:

Color, sequence, or sequence of color, optional

So this way you will be using the array a to select values from the colormap which will in turn be normalized by the ,ax and min values in a.

Upvotes: 3

Related Questions