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

Matplotlib colorbar传location参数报unexpected keyword argument错如何解决

报错原因

location是fig.colorbar()方法的专属参数,仅在你没有手动指定cax、让Matplotlib自动为colorbar创建绘图轴时生效。当你已经通过divider.append_axes()提前创建好了专门放置colorbar的轴cax,相当于已经明确指定了colorbar的位置、大小、和主图的间距,此时colorbar初始化不再需要location参数,直接传入该参数会因为Colorbar类本身没有对应参数而抛出类型错误。

实现方案

直接删除fig.colorbar()调用中的location参数即可,你已经通过divider.append_axes("left", size="5%", pad=0.05)指定了在主图左侧创建colorbar轴,colorbar会自动渲染在左侧,调整pad参数的数值就可以任意控制colorbar和主图的间距:

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots(1, 1)

im = plt.imshow(np.arange(0, 100).reshape(10, 10))
ax.set_xticklabels([])
ax.set_yticklabels([])

divider = make_axes_locatable(ax)
# pad参数直接控制colorbar和主图的间距,数值越小间距越小
cax = divider.append_axes("left", size="5%", pad=0.05)
# 移除location参数即可正常运行
colorbar = fig.colorbar(im, cax=cax)
colorbar.set_label('y label')
plt.show()

如果需要将colorbar的刻度和标签放置在远离主图的左侧,可额外添加配置:

# 将刻度移动到colorbar左侧
cax.yaxis.set_ticks_position('left')
# 调整标签和刻度的间距
colorbar.set_label('y label', labelpad=10)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:24:00