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

Matplotlib报错:'LinearSegmentedColormap'对象无'resampled'属性

解决Matplotlib中resampled方法的AttributeError问题

问题原因

resampled()是Matplotlib 3.7.0版本新增的API,你本地Jupyter Notebook里的Matplotlib版本低于这个版本,所以触发了AttributeError: 'LinearSegmentedColormap' object has no attribute 'resampled'错误。而Colab会持续更新库版本,因此能正常运行这段官方文档代码。

解决方案

方案1:升级Matplotlib

在Jupyter的代码单元格或终端中执行升级命令:

!pip install --upgrade matplotlib

升级完成后重启Jupyter内核,再运行原代码即可。

方案2:兼容旧版本的替代写法

如果不想升级版本,可以用以下两种方式替代resampled():

方式A:使用内部_resample方法

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib as mpl
from matplotlib.colors import LinearSegmentedColormap, ListedColormap

# Color map
top = mpl.colormaps['Oranges_r']._resample(128)
bottom = mpl.colormaps['Blues']._resample(128)

newcolors = np.vstack((top(np.linspace(0, 1, 128)),
                       bottom(np.linspace(0, 1, 128))))
newcmp = ListedColormap(newcolors, name='OrangeBlue')

注意:_resample是内部方法,未来版本可能会变更,但在低于3.7.0的版本中可以正常使用。

方式B:手动实现重采样逻辑

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib as mpl
from matplotlib.colors import LinearSegmentedColormap, ListedColormap

# 自定义重采样函数
def resample_cmap(cmap, num_colors):
    return LinearSegmentedColormap.from_list(
        f"{cmap.name}_resampled{num_colors}",
        cmap(np.linspace(0, 1, num_colors))
    )

# Color map
top = resample_cmap(mpl.colormaps['Oranges_r'], 128)
bottom = resample_cmap(mpl.colormaps['Blues'], 128)

newcolors = np.vstack((top(np.linspace(0, 1, 128)),
                       bottom(np.linspace(0, 1, 128))))
newcmp = ListedColormap(newcolors, name='OrangeBlue')

这个写法不依赖内部方法,兼容性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:32:49