Qualitative Colormaps in Matplotlib Visualization#

https://matplotlib.org/stable/tutorials/colors/colormaps.html

  • Matplotlib has a number of built-in colormaps accessible via matplotlib.cm.get_cmap.

  • There are also external libraries that have many extra colormaps, which can be viewed in the Third-party colormaps section of the Matplotlib documentation.

import matplotlib.pyplot as plt
import numpy as np

使用for循环逐个添加颜色#

NUM_COLORS = 20

cm = plt.get_cmap('gist_rainbow')
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(NUM_COLORS):
    lines = ax.plot(np.arange(10)*(i+1))
    lines[0].set_color(cm(i//3*3.0/NUM_COLORS))
    lines[0].set_linewidth(i%3 + 1)

#fig.savefig('moreColors.png')
plt.show()
_images/550bfe7348c3b0ddef7fb2540dd58778075e3ab12680e2e61ba45ddfa6660320.png

我们会更加推荐使用tab20这一colormap。

NUM_COLORS = 20
cm = plt.get_cmap('tab20')

fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(NUM_COLORS):
    lines = ax.plot(np.arange(10)*(i+1))
    lines[0].set_color(cm(i))
    lines[0].set_linewidth(5)

#fig.savefig('moreColors.png')
plt.show()
_images/f151ceb0083bd0ba51b0ba1ada78a32cc8a4992fee2f34cc63e00643be9cb1fb.png
cm
tab20
tab20 colormap
under
bad
over
NUM_COLORS = 20
cm = plt.get_cmap('tab20b')

fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(NUM_COLORS):
    lines = ax.plot(np.arange(10)*(i+1))
    lines[0].set_color(cm(i))
    lines[0].set_linewidth(5)

#fig.savefig('moreColors.png')
plt.show()
_images/570883ee6608eda5bea7c80c0079e6df6ff75aba629551e9b7606173908db43f.png
cm
tab20b
tab20b colormap
under
bad
over
NUM_COLORS = 20
cm = plt.get_cmap('tab20c')

fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(NUM_COLORS):
    lines = ax.plot(np.arange(10)*(i+1))
    lines[0].set_color(cm(i))
    lines[0].set_linewidth(5)

#fig.savefig('moreColors.png')
plt.show()
_images/4bf534e1ca0ab8e7bc47e6bf91a2a5b088573afb7eed6f10ec06092fedc88c82.png
cm
tab20c
tab20c colormap
under
bad
over

从ColorMap中选择N个颜色#

# Create data
X = np.arange(0, 10, 1)
Y = X + 5 * np.random.random((20, X.size))

cm = plt.get_cmap('tab20')
plt.stackplot(X, Y, colors = cm.colors[:len(Y)]);
_images/960c5e4b2b0762a0a092b77be3ff8473b85c7278c229304f80e0fdc2822e7c85.png
cm = plt.get_cmap('tab20')

plt.figure(figsize = [10, 10])
for k, i in enumerate(Y):
    plt.plot(X, i, color = cm(k), linewidth = 5, label = str(k))
plt.legend()
plt.show()
_images/3ec2a1acc8165def35687d2d616e1d7fb0ae2de5555c213f6a36358e532734a0.png