Skip to content

Instantly share code, notes, and snippets.

@gVallverdu
Last active November 10, 2018 11:10
Show Gist options
  • Save gVallverdu/ac3efecfc640cc9e107f1f7cbfb11bb4 to your computer and use it in GitHub Desktop.
Save gVallverdu/ac3efecfc640cc9e107f1f7cbfb11bb4 to your computer and use it in GitHub Desktop.
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
@gVallverdu
Copy link
Author

gVallverdu commented Nov 16, 2016

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

@hzxie
Copy link

hzxie commented Nov 10, 2018

I got following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "plot_cmap.py", line 21, in plot_cmap
    with mpl.rc_context(mpl.rcParamsDefault):
NameError: name 'mpl' is not defined

I fixed it by adding

import matplotlib as mpl
import numpy as np

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