You need to enable JavaScript to run this app. Matplotlib散点图添加speed维度Colorbar报缺少mappable参数咨询
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib散点图添加speed维度Colorbar报缺少mappable参数咨询

报错原因

你遇到的missing 1 required positional argument: 'mappable'报错,核心原因是调用Colorbar方法时没有传入要求的关联对象。
这里提到的mappable,本质是绑定了颜色映射规则的可视化元素实例。matplotlib的Colorbar不会凭空生成,必须关联一个已经绘制好的、带色值关联的图形(比如散点、热力图),才能自动匹配色值范围、对应数值刻度生成色条。
你之前的代码里,ax.scatter()运行后会自动生成符合要求的mappable对象,但没有把这个返回值存下来,直接调用fig.colorbar(ax=ax)时,程序找不到要关联的色值数据源,自然触发参数缺失报错。

修正方法

  • 第一步,保存scatter绘图的返回值。把原来写散点图的代码修改为接收返回对象:
    scatter_obj = ax.scatter(
        x=df_sample.duration.values, 
        y=df_sample.distance.values, 
        c=df_sample.speed.values, 
        cmap=cm.YlGnBu
    )
    
  • 第二步,调用Colorbar时传入保存的对象。把最后一行代码修改为:
    fig.colorbar(mappable=scatter_obj, ax=ax)
    
    注:你选用的cm.YlGnBu色卡本身就是从浅黄色(低数值)渐变到深蓝色(高数值),完全匹配“黄色对应最慢速度、蓝色对应最快速度”的需求,不需要额外调整色卡规则。

修正后可直接运行的完整代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

with plt.style.context('seaborn-ticks'):

    fig, ax = plt.subplots(figsize=(10, 6))

    ax.set_title(
        'Relationship between Distance & Duration', 
        fontdict={'fontsize': 18, 'fontweight': 'bold'}, 
        loc='left', 
        pad=20
    )
    # 接收散点图返回的mappable对象
    scatter_obj = ax.scatter(
        x=df_sample.duration.values, 
        y=df_sample.distance.values, 
        c=df_sample.speed.values, 
        cmap=cm.YlGnBu
    )

    # 隐藏顶部和右侧边框
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)

    # 边框向外偏移5个单位,等效于sns.despine(offset=5)
    ax.spines['left'].set_position(('outward', 5))
    ax.spines['left'].set_linewidth(1.2)
    ax.spines['bottom'].set_position(('outward', 5))
    ax.spines['bottom'].set_linewidth(1.2)
    
    # 设置坐标轴刻度
    xloc = np.arange(0, 45, 5)
    ax.set_xticks(xloc)
    ax.set_xticklabels(labels=xloc, fontdict={'fontsize': 12})
    ax.set_xlabel('Minute(s)', fontdict={'fontsize': 14, 'fontweight': 'bold'})
    
    yloc = np.arange(6)
    ylab = [f"{int(num)}" for num in yloc]
    ax.set_yticks(yloc)
    ax.set_yticklabels(labels=ylab, fontdict={'fontsize': 12})
    ax.set_ylabel("Distance (KM)", fontdict={'fontsize': 14, 'fontweight': 'bold'})
    
    # 传入关联的mappable对象生成色条
    fig.colorbar(mappable=scatter_obj, ax=ax)

内容的提问来源于stack exchange,提问作者Ong K.S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.03 08:06:03