强基初中数学&学Python——第286课 数字和数学第三方模块Matplotlib之九:颜色-选择颜色映射(3)

Matplotlib颜色映射的亮度  在这里,我们测试matplotlib颜色映射的亮度值。请注意,有一些关于颜色映射的文档([list-colormaps])。

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

import numpy as npimport matplotlib as mplimport matplotlib.pyplot as pltfrom colorspacious import cspace_converter
cmaps = {}
def plot_color_gradients(category, cmap_list):    # Save colormap list for later.    cmaps[category] = cmap_list
plot_color_gradients('Perceptually Uniform Sequential',                     ['viridis', 'plasma', 'inferno', 'magma', 'cividis'])plot_color_gradients('Sequential',                     ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',                      'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',                      'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn'])plot_color_gradients('Sequential (2)',                     ['binary', 'gist_yarg', 'gist_gray', 'gray', 'bone',                      'pink', 'spring', 'summer', 'autumn', 'winter', 'cool',                      'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper'])plot_color_gradients('Diverging',                     ['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu',                      'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic'])plot_color_gradients('Cyclic', ['twilight', 'twilight_shifted', 'hsv'])plot_color_gradients('Miscellaneous',                     ['flag', 'prism', 'ocean', 'gist_earth', 'terrain',                      'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap',                      'cubehelix', 'brg', 'gist_rainbow', 'rainbow', 'jet',                      'turbo', 'nipy_spectral', 'gist_ncar'])plot_color_gradients('Qualitative',                     ['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2',                      'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b',                      'tab20c'])
mpl.rcParams.update({'font.size': 12})
# Number of colormap per subplot for particular cmap categories_DSUBS = {'Perceptually Uniform Sequential': 5, 'Sequential': 6,          'Sequential (2)': 6, 'Diverging': 6, 'Cyclic': 3,          'Qualitative': 4, 'Miscellaneous': 6}
# Spacing between the colormaps of a subplot_DC = {'Perceptually Uniform Sequential': 1.4, 'Sequential': 0.7,       'Sequential (2)': 1.4, 'Diverging': 1.4, 'Cyclic': 1.4,       'Qualitative': 1.4, 'Miscellaneous': 1.4}
# Indices to step through colormapx = np.linspace(0.0, 1.0, 100)
# Do plotfor cmap_category, cmap_list in cmaps.items():
    # Do subplots so that colormaps have enough space.    # Default is 6 colormaps per subplot.    dsub = _DSUBS.get(cmap_category, 6)    nsubplots = int(np.ceil(len(cmap_list) / dsub))
    # squeeze=False to handle similarly the case of a single subplot    fig, axs = plt.subplots(nrows=nsubplots, squeeze=False,                            figsize=(7, 2.6*nsubplots))
    for i, ax in enumerate(axs.flat):
        locs = []  # locations for text labels
        for j, cmap in enumerate(cmap_list[i*dsub:(i+1)*dsub]):
            # Get RGB values for colormap and convert the colormap in            # CAM02-UCS colorspace.  lab[0, :, 0] is the lightness.            rgb = mpl.colormaps[cmap](x)[np.newaxis, :, :3]            lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)
            # Plot colormap L values.  Do separately for each category            # so each plot can be pretty.  To make scatter markers change            # color along plot:            # https://stackoverflow.com/q/8202605/
            if cmap_category == 'Sequential':                # These colormaps all start at high lightness, but we want them                # reversed to look nice in the plot, so reverse the order.                y_ = lab[0, ::-1, 0]                c_ = x[::-1]            else:                y_ = lab[0, :, 0]                c_ = x
            dc = _DC.get(cmap_category, 1.4)  # cmaps horizontal spacing            ax.scatter(x + j*dc, y_, c=c_, cmap=cmap, s=300, linewidths=0.0)
            # Store locations for colormap labels            if cmap_category in ('Perceptually Uniform Sequential',                                 'Sequential'):                locs.append(x[-1] + j*dc)            elif cmap_category in ('Diverging', 'Qualitative', 'Cyclic',                                   'Miscellaneous', 'Sequential (2)'):                locs.append(x[int(x.size/2.)] + j*dc)
        # Set up the axis limits:        #   * the 1st subplot is used as a reference for the x-axis limits        #   * lightness values goes from 0 to 100 (y-axis limits)        ax.set_xlim(axs[0, 0].get_xlim())        ax.set_ylim(0.0, 100.0)
        # Set up labels for colormaps        ax.xaxis.set_ticks_position('top')        ticker = mpl.ticker.FixedLocator(locs)        ax.xaxis.set_major_locator(ticker)        formatter = mpl.ticker.FixedFormatter(cmap_list[i*dsub:(i+1)*dsub])        ax.xaxis.set_major_formatter(formatter)        ax.xaxis.set_tick_params(rotation=50)        ax.set_ylabel('Lightness $L^*$', fontsize=12)
    ax.set_xlabel(cmap_category + ' colormaps', fontsize=14)
    fig.tight_layout(h_pad=0.0, pad=1.5)    plt.show()

 

 

 

 

 

 

灰度转换  关注彩色图的灰度转换是很重要的,因为它们可以在黑白打印机上打印。如果不仔细考虑,你的读者可能会得到难以辨认的图,因为灰度在颜色映射中的变化是不可预测的。  转换为灰度可以用很多不同的方式完成[bw]。一些更好的方法使用像素的rgb值的线性组合,但根据我们感知颜色强度的方式进行加权。转换为灰度的非线性方法是使用像素的L*值。一般来说,类似的原则适用于这个问题,就像它们表现人们感知信息一样;也就是说,如果选择了在L*值单调增加的颜色映射,它将以合理的方式打印为灰度。  考虑到这一点,我们可以看到序列颜色映射在灰度级中有合理的表示。有些序列2(Sequential2)颜色映射具有足够好的灰度表示,尽管有些(autumn(秋季)、spring(春季)、summer(夏季)、winter(冬季))的灰度变化非常小。如果在绘图中使用这样的颜色映射,然后将绘图打印为灰度图,则许多信息可能会映射到相同的灰度值。分散颜色映射的变化主要是从外边缘的深灰色到在中间的白色。有些(PuOr和seismic)一侧的灰色明显比另一侧深,因此不是很对称。coolwarn的灰度范围很小,打印出来的图会更均匀,会丢失很多细节。请注意,重叠的标记轮廓有助于区分颜色图的一侧与另一侧,因为一旦将绘图打印为灰度级,就无法使用颜色。许多定性和混杂颜色映射,如Accent、hsv、jet和turbo,在整个颜色映射中从较深变为较浅,再变回较深的灰色。一旦绘图以灰度打印,这将使观看者无法领会绘图中的信息。

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

import numpy as npimport matplotlib as mplimport matplotlib.pyplot as plt from colorspacious import cspace_converter
cmaps = {}
def plot_color_gradients(category, cmap_list):    # Save colormap list for later.    cmaps[category] = cmap_list
plot_color_gradients('Perceptually Uniform Sequential',                     ['viridis', 'plasma', 'inferno', 'magma', 'cividis'])plot_color_gradients('Sequential',                     ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',                      'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',                      'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn'])plot_color_gradients('Sequential (2)',                     ['binary', 'gist_yarg', 'gist_gray', 'gray', 'bone',                      'pink', 'spring', 'summer', 'autumn', 'winter', 'cool',                      'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper'])plot_color_gradients('Diverging',                     ['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu',                      'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic'])plot_color_gradients('Cyclic', ['twilight', 'twilight_shifted', 'hsv'])plot_color_gradients('Miscellaneous',                     ['flag', 'prism', 'ocean', 'gist_earth', 'terrain',                      'gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap',                      'cubehelix', 'brg', 'gist_rainbow', 'rainbow', 'jet',                      'turbo', 'nipy_spectral', 'gist_ncar'])plot_color_gradients('Qualitative',                     ['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2',                      'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b',                      'tab20c'])mpl.rcParams.update({'font.size': 14})
# Indices to step through colormap.x = np.linspace(0.0, 1.0, 100)
gradient = np.linspace(0, 1, 256)gradient = np.vstack((gradient, gradient))

def plot_color_gradients(cmap_category, cmap_list):    fig, axs = plt.subplots(nrows=len(cmap_list), ncols=2)    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99,                        wspace=0.05)    fig.suptitle(cmap_category + ' colormaps', fontsize=14, y=1.0, x=0.6)
    for ax, name in zip(axs, cmap_list):
        # Get RGB values for colormap.        rgb = mpl.colormaps[name](x)[np.newaxis, :, :3]
        # Get colormap in CAM02-UCS colorspace. We want the lightness.        lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)        L = lab[0, :, 0]        L = np.float32(np.vstack((L, L, L)))
        ax[0].imshow(gradient, aspect='auto', cmap=mpl.colormaps[name])        ax[1].imshow(L, aspect='auto', cmap='binary_r', vmin=0., vmax=100.)        pos = list(ax[0].get_position().bounds)        x_text = pos[0] - 0.01        y_text = pos[1] + pos[3]/2.        fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)
    # Turn off *all* ticks & spines, not just the ones with colormaps.    for ax in axs.flat:        ax.set_axis_off()
    plt.show()

for cmap_category, cmap_list in cmaps.items():
    plot_color_gradients(cmap_category, cmap_list)

 

 

 

 

 

 

 

色觉缺陷  有很多关于色盲的信息(例如[colorblindness])。此外,还有一些工具可以将图像转换为不同类型色觉缺陷者能看得到得样子。

  色觉缺陷最常见的表现形式是区分红色和绿色。因此,避免同时使用红色和绿色的颜色映射通常会避免许多问题。

list-colormaps:

https://matplotlib.org/stable/tutorials/colors/colormaps.html#list-colormaps

bw:

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

mpl.rcParams.update:

https://docs.python.org/3/library/stdtypes.html#dict.update

colorblindness:

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