python colormap quantisation (matplotlib)

2020-08-01 06:19发布

问题:

I have the following colormap in Python which maps each value to a color. But my question: How can I quantize the values for getting a same color for a specified range? For example: from 0 until 10 (Green) , from 10 until 50 (yellow), from 50 until 55 (red) , ...

import matplotlib as mpl
import matplotlib
from matplotlib import cm
.
.
.
norm = matplotlib.colors.Normalize(vmin = min,vmax = max, clip = True)
.
.
for i in range(numberMaterials):
    step = (max-min)/numberMaterials
    value = min + step*i
    mat = bpy.data.materials.new("mat" +str(i))
    color = cm.jet(norm(value),bytes=True)

回答1:

It seems you are asking for a BoundaryNorm.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors


cmap = matplotlib.colors.ListedColormap(["limegreen", "gold", "crimson"])
norm = matplotlib.colors.BoundaryNorm([0,10,50,55], 3)

x = np.linspace(0,55)

fig, (ax, ax2) = plt.subplots(ncols=2)
sc = ax.scatter(x,x, c=x, cmap=cmap, norm=norm)
fig.colorbar(sc, ax=ax, spacing="uniform")

sc2 = ax2.scatter(x,x, c=x, cmap=cmap, norm=norm)
fig.colorbar(sc2, ax=ax2, spacing="proportional")

plt.show()