corpus_callosum
corpus_callosum

Reputation: 11

Is there a way to convert scalar values in an array to matplotlib colormap indices?

I have an array that consists of a bunch of floats (e.g. [1202.21, -124.4, 23, ....]) that I've plotted with matplotlib using the colormap jet. Is there any way to get the indices of the jet scale (i.e. a single value 0-255) for each float in my array? I want to display some stats about the data but it only will make sense if the stats (mean, standard deviation, etc.) are within the 0-255 range.

I've tried returning the array used by matplotlib using get_array() but that doesn't seem to change the data.

Thanks!

Upvotes: 0

Views: 680

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339710

numpy.digitize gives you the bin number for the data when put into bins. Here you have 256 bins and the last bin is closed. Hence,

import numpy as np

a = np.array([1,2,3])

N = 256
bins = np.linspace(a.min(), a.max(), N+1)
dig = np.digitize(a, bins)-1
dig[dig == N] = N-1 # map the last half-open interval back
print(dig)

Now verify that those are indeed the indices of the colormap:

import matplotlib.pyplot as plt

cmap = plt.cm.jet
norm = plt.Normalize(a.min(), a.max())
colors1 = cmap(norm(a))

colors2 = cmap(dig)

assert(np.all(colors1 == colors2))

Upvotes: 1

Related Questions