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
相关产品推荐
相关产品推荐

