简体   繁体   English

如何使用 matplotlib 以特定值定义颜色来创建线性颜色图?

[英]How to create a linear colormap with color defined at specific values with matplotlib?

I would like to create a colormap that fade linearly through colors defined for specific values.我想创建一个颜色图,它通过为特定值定义的 colors 线性淡化。 Below here is my Minimal Non Working Example.下面是我的最小非工作示例。

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

data = np.random.uniform(0, 10, (10, 10))

values = [0., 0.8, 1., 10.]
colors = ["#ff0000", "#00ff00", "#0000ff", "#cccccc"]

I have the feeling this can be solved by using cmap and norm switches when plotting with imshow but I could not succeed to have a smooth gradient of colors passing by defined colors at values.我觉得这可以通过在使用imshow绘图时使用cmapnorm开关来解决,但我无法成功地使 colors 的平滑梯度通过定义的 colors 值。

cmap = mpl.colors.ListedColormap(colors, name="mycmap")
norm = mpl.colors.BoundaryNorm(values, len(colors))

fig, axe  = plt.subplots()
cmap_ = axe.imshow(data, aspect="auto", origin="upper", cmap=cmap, norm=norm)
cbar = fig.colorbar(cmap_, ax=axe)

Also the scale is then non linear.比例尺也是非线性的。

在此处输入图像描述

How can I setup this colormap using the provided values and colors above?如何使用上面提供的值和 colors 设置此颜色图?

Here is the current solution I have found to solve my problem:这是我找到的解决问题的当前解决方案:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
    
def get_colormap(values, colors, name="custom"):
    values = np.sort(np.array(values))
    values = np.interp(values, (values.min(), values.max()), (0., 1.))
    cmap = mpl.colors.LinearSegmentedColormap.from_list(name, list(zip(values, colors)))
    return cmap

data = np.random.uniform(0, 10, (10, 10))
values = np.array([0., 0.8, 1., 10.])
colors = ["#ff0000", "#00ff00", "#0000ff", "#cccccc"]
cmap_ = get_colormap(values, colors)

fig, axe  = plt.subplots()
cmap = axe.imshow(data, aspect="auto", origin="upper", cmap=cmap_)
cbar = fig.colorbar(cmap, ax=axe)

Not straightforward but functional.不简单但实用。 I'll keep the question unanswered to leave opportunity to best solution to come.我将保留未回答的问题,以便有机会找到最佳解决方案。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM