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

Matplotlib调用plt.colorbar报错“No mappable found”的原因解析

问题描述

我编写了一段Python脚本生成对应图像,但将plt.colorbar放在倒数第二行时,出现错误提示:No mappable was found to use for colorbar creation.。脚本代码如下:

jet = plt.get_cmap('viridis')
cNorm = colors.Normalize(vmin=np.min(Mall), vmax=np.max(Mall))
scalarMap = cmx.ScalarMappable(norm=cNorm,cmap = jet)

x_fill1 = [0, 0, x[0, 1]]
y_fill1 = [0, 1, y[0, 1]]
x_fill4 = [x[0, n], x2[0, 1], 0]
y_fill4 = [y[0, n], y2[0, 1], 1]
x_fill8 = np.array([x[n-2, n-1], x[n-2, n], x[n-1, n]])
y_fill8 = np.array([y[n-2, n-1], y[n-2, n], y[n-1, n]])
plt.fill(x_fill1, y_fill1, color=scalarMap.to_rgba(Mall[0]))
plt.fill(x_fill4, y_fill4, color=scalarMap.to_rgba(Mall[n]))
plt.fill(x_fill8, y_fill8, color=scalarMap.to_rgba(Mall[int(n*(n+3) / 2 - 1)]))


for i in range(1,n):  # for n = 3 region 1 till 4
    colorVal = scalarMap.to_rgba(Mall[i])
    x_fill = [0., x[0, i], x[0, i + 1]]
    y_fill = [1., y[0, i], y[0, i + 1]]
    plt.fill(x_fill, y_fill, color=colorVal)

for i in range(n-2):  #
    colorVal = scalarMap.to_rgba(M[i + 1, i + 1])
    x_fill = np.array([x[i, i + 1], x[i, i + 2], x[i + 1, i + 2]])
    y_fill = np.array([y[i, i + 1], y[i, i + 2], y[i + 1, i + 2]])
    plt.fill(x_fill, y_fill, color=colorVal)
    for j in range(i+1, n-1):
        colorVal = scalarMap.to_rgba(M[i + 1, j + 1])
        x_fill = np.array([x[i, j + 1], x[i + 1, j + 1], x[i + 1, j + 2], x[i, j + 2]])
        y_fill = np.array([y[i, j + 1], y[i + 1, j + 1], y[i + 1, j + 2], y[i, j + 2]])
        plt.fill(x_fill, y_fill, color=colorVal)
        colorVal = scalarMap.to_rgba(M[i + 1, j])
        x_fill = np.array([x[i, j], x[i, j + 1], x[i + 1, j + 1]])
        y_fill = np.array([x[i, j], x[i, j + 1], x[i + 1, j + 1]])
        plt.fill(x_fill, y_fill, color=colorVal)


plt.ylim(0, 2.4)
#plt.colorbar(orientation='vertical', label='mach number')
plt.show()

对应生成的图像:
图像展示

错误原因

你通过scalarMap.to_rgba()将数值转换为具体的RGB颜色值,直接传递给plt.fill()的color参数——这种方式是手动指定填充颜色,没有把颜色映射关系关联到任何绘图对象上。

plt.colorbar()默认需要找到一个带有颜色映射(mappable)的绘图元素(比如imshow、scatter这类自带cmap参数的函数返回的对象),才能生成对应的色条。而你创建的ScalarMappable对象scalarMap只是用来计算颜色,并没有被注册到当前绘图轴中,所以Matplotlib找不到可关联的mappable对象,从而抛出错误。

解决方法

有两种简单的修复方式:

  • 直接传入scalarMap给colorbar
    明确告诉plt.colorbar()使用你创建好的颜色映射对象:
    plt.colorbar(scalarMap, orientation='vertical', label='mach number')
    
  • 给scalarMap设置空数组
    在创建scalarMap后添加一行代码,让Matplotlib识别到这个映射对象:
    scalarMap = cmx.ScalarMappable(norm=cNorm,cmap = jet)
    scalarMap.set_array([])  # 添加此行
    # 后续绘图代码不变
    plt.colorbar(orientation='vertical', label='mach number')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:45:38