Matplotlib 较暗的 HSV 颜色图

标签 matplotlib colors hsv color-mapping

我正在使用 matplotlib 中的 HSV 颜色图来绘制一些向量场。有没有办法使 HSV 颜色变暗或变得更平滑,使它们看起来更像这样

enter image description here

比我原来的绘图颜色太亮:

enter image description here

最佳答案

简介

假设您正在尝试绘制这样的 pcolor 图像:

import numpy as np
import matplotlib.pyplot as plt

y, x = np.mgrid[slice(-3, 3 + 0.05, 0.05),
                slice(-3, 3 + 0.15, 0.15)]
z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
z = z[:-1, :-1]

fig = plt.figure(1)
fig.clf()
ax = plt.gca()
pcol = ax.pcolormesh(x, y, z, cmap=plt.get_cmap('hsv'), )
plt.colorbar(pcol)
ax.set_xlim([-3, 3])
ax.set_ylim([-3, 3])

您的图像将是:

HSV colormap.

方法

我编写了 MPL cookbook cmap_map function 的替代实现修改颜色图。除了支持 kwargs 和 pep8 合规性之外,此版本还处理颜色图中的不连续性:

import numpy as np
from matplotlib.colors import LinearSegmentedColormap as lsc


def cmap_map(function, cmap, name='colormap_mod', N=None, gamma=None):
    """
    Modify a colormap using `function` which must operate on 3-element
    arrays of [r, g, b] values.

    You may specify the number of colors, `N`, and the opacity, `gamma`,
    value of the returned colormap. These values default to the ones in
    the input `cmap`.

    You may also specify a `name` for the colormap, so that it can be
    loaded using plt.get_cmap(name).
    """
    if N is None:
        N = cmap.N
    if gamma is None:
        gamma = cmap._gamma
    cdict = cmap._segmentdata
    # Cast the steps into lists:
    step_dict = {key: map(lambda x: x[0], cdict[key]) for key in cdict}
    # Now get the unique steps (first column of the arrays):
    step_list = np.unique(sum(step_dict.values(), []))
    # 'y0', 'y1' are as defined in LinearSegmentedColormap docstring:
    y0 = cmap(step_list)[:, :3]
    y1 = y0.copy()[:, :3]
    # Go back to catch the discontinuities, and place them into y0, y1
    for iclr, key in enumerate(['red', 'green', 'blue']):
        for istp, step in enumerate(step_list):
            try:
                ind = step_dict[key].index(step)
            except ValueError:
                # This step is not in this color
                continue
            y0[istp, iclr] = cdict[key][ind][1]
            y1[istp, iclr] = cdict[key][ind][2]
    # Map the colors to their new values:
    y0 = np.array(map(function, y0))
    y1 = np.array(map(function, y1))
    # Build the new colormap (overwriting step_dict):
    for iclr, clr in enumerate(['red', 'green', 'blue']):
        step_dict[clr] = np.vstack((step_list, y0[:, iclr], y1[:, iclr])).T
    return lsc(name, step_dict, N=N, gamma=gamma)

实现

要使用它,只需定义一个函数来修改您的 RGB colors根据您的喜好(值从 0 到 1)并将其作为输入提供给 cmap_map。例如,要使颜色接近您提供的图像中的颜色,您可以定义:

def darken(x, ):
   return x * 0.8

dark_hsv = cmap_map(darken, plt.get_cmap('hsv'))

然后修改对pcolormesh的调用:

pcol = ax.pcolormesh(x, y, z, cmap=dark_hsv)

Darker HSV.

如果您只想使图像中的绿色变暗,您可以这样做(现在全部在一行中):

pcol = ax.pcolormesh(x, y, z,
                     cmap=cmap_map(lambda x: x * [1, 0.7, 1],
                                   plt.get_cmap('hsv'))
                    )

Darken green only

关于Matplotlib 较暗的 HSV 颜色图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31321967/

相关文章:

python - matplotlib imshow 为每种颜色添加标签并将它们放入图例中

css - 使用 CSS 表 (GTK+3) 更改 GtkToggleToolButton 的文本颜色

android - 无法让 Color.HSVToColor 在 Android 上工作

c++ - 如何更改 QGraphicsView 所选项目的颜色

c++ - 使用 inRange 后在 openCV 中从 HSV 转换为 BGR 或从 HSV 转换为 JPEG 时出错

android - 尝试使用 opencv 从图像中检测蓝色,并得到意想不到的结果

python - 使用 matplotlib 绘制百分位数

python - Axes3d 与 axes3d matplotlib

python - 如何更改子图中线条的颜色?

java - 如何自动生成N "distinct"种颜色?