You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对Matplotlib中ListedColormap的自定义颜色进行插值?

问题解答

首先要注意:你代码里的RGB颜色值是0-255范围的,Matplotlib的颜色映射要求颜色值归一到0-1区间,所以首先要把每个颜色分量除以255,不然显示的颜色会完全不对。

针对你的问题,分两种方案解决:

方案1:用Matplotlib原生的线性插值色彩映射(推荐)

ListedColormap是离散型的,默认只会取最近匹配的颜色。但Matplotlib提供了LinearSegmentedColormap,可以直接基于你的自定义颜色列表生成线性插值的渐变色彩映射,完全满足需求。

修改后的代码如下:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
from cmath import phase

s = 10
row, col = np.indices((s * 2, s * 2))
z = (col - s) + (row - s) * 1j

# 先把RGB颜色归一到0-1区间
colors = np.array([[5, 175, 242],
                   [132, 191, 4],
                   [242, 159, 5],
                   [242, 62, 22],
                   [175, 114, 211]]) / 255

# 用LinearSegmentedColormap生成线性插值的颜色映射
color_map = LinearSegmentedColormap.from_list("custom_gradient", colors)

ax1 = plt.subplot()
space = [-s, s, -s, s]
# 用np.angle替代np.vectorize(phase),效率更高
ax1.imshow(np.angle(z), extent=space, cmap=color_map)
plt.show()

方案2:预插值颜色后传入ListedColormap

如果一定要用ListedColormap,你可以手动对颜色列表进行线性插值,生成足够多的颜色点,再传给ListedColormap,用大量离散颜色模拟渐变效果:

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
from cmath import phase

s = 10
row, col = np.indices((s * 2, s * 2))
z = (col - s) + (row - s) * 1j

# 原始颜色(归一到0-1)
base_colors = np.array([[5, 175, 242],
                        [132, 191, 4],
                        [242, 159, 5],
                        [242, 62, 22],
                        [175, 114, 211]]) / 255

# 预插值生成256个颜色点
num_interp = 256
# 生成每个原始颜色对应的位置(0到1之间)
positions = np.linspace(0, 1, len(base_colors))
# 对每个RGB通道分别插值
interp_colors = np.zeros((num_interp, 3))
for i in range(3):
    interp_colors[:, i] = np.interp(np.linspace(0, 1, num_interp), positions, base_colors[:, i])

# 用插值后的颜色创建ListedColormap
color_map = ListedColormap(interp_colors)

ax1 = plt.subplot()
space = [-s, s, -s, s]
ax1.imshow(np.angle(z), extent=space, cmap=color_map)
plt.show()

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:05:17