Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A convenient function to show a matplotlib color map
import matplotlib.pyplot as plt
def plot_cmap(cmap, ncolor):
"""
A convenient function to plot colors of a matplotlib cmap
Args:
ncolor (int): number of color to show
cmap: a cmap object or a matplotlib color name
"""
if isinstance(cmap, str):
try:
cm = plt.get_cmap(cmap)
except ValueError:
print("WARNINGS :", cmap, " is not a known colormap")
cm = plt.cm.gray
else:
cm = cmap
with mpl.rc_context(mpl.rcParamsDefault):
fig = plt.figure(figsize=(6, 1), frameon=False)
ax = fig.add_subplot(111)
ax.pcolor(np.linspace(1, ncolor, ncolor).reshape(1, ncolor), cmap=cm)
ax.set_title(cm.name)
xt = ax.set_xticks([])
yt = ax.set_yticks([])
return fig
def show_colors(colors):
"""
Draw a square for each color contained in the colors list
given in argument.
"""
with plt.rc_context(plt.rcParamsDefault):
fig = plt.figure(figsize=(6, 1), frameon=False)
ax = fig.add_subplot(111)
for x, color in enumerate(colors):
ax.add_patch(
mpl.patches.Rectangle(
(x, 0), 1, 1, facecolor=color
)
)
ax.set_xlim((0, len(colors)))
ax.set_ylim((0, 1))
ax.set_xticks([])
ax.set_yticks([])
ax.set_aspect("equal")
return fig
Owner

gVallverdu commented Nov 16, 2016 edited

Common usage :

plot cmap

fig = plot_cmap("summer", 6)
fig.savefig("cm.png", bbox_inches="tight")

cm

show colors

palette = plt.cm.summer(X=[1, 50, 100, 200], alpha=.6)
print(palette)
show_colors(palette)

result :

 [ 0.19607843  0.59803922  0.4         0.6       ]
 [ 0.39215686  0.69607843  0.4         0.6       ]
 [ 0.78431373  0.89215686  0.4         0.6       ]]

mpl_palette1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment