Matplotlib colorbar:__init__() 得到了一个意外的关键字参数 'location'

Matplotlib colorbar: __init__() got an unexpected keyword argument 'location'

我试图按照此处给出的示例在轴的左侧绘制一个 matplotlib 颜色条:https://matplotlib.org/stable/gallery/axes_grid1/simple_colorbar.html#sphx-glr-gallery-axes-grid1-simple-colorbar-py

但是因为我想在轴的左侧设置颜色条,所以我尝试了:

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)
cax = divider.append_axes("left", size="5%", pad=0.05)
colorbar = fig.colorbar(im, cax=cax, location='left')
colorbar.set_label('y label')

这给了我以下异常:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-89d8edf2c11c> in <module>
     11 divider = make_axes_locatable(ax)
     12 cax = divider.append_axes("left", size = "5%", pad = 0.05)
---> 13 colorbar = fig.colorbar(im, cax = cax, location = 'left')
     14 colorbar.set_label('y label')
     15 

~\Anaconda3\envs\data-evaluation\lib\site-packages\matplotlib\figure.py in colorbar(self, mappable, cax, ax, use_gridspec, **kw)
   1171                              'panchor']
   1172         cb_kw = {k: v for k, v in kw.items() if k not in NON_COLORBAR_KEYS}
-> 1173         cb = cbar.Colorbar(cax, mappable, **cb_kw)
   1174 
   1175         self.sca(current_ax)

~\Anaconda3\envs\data-evaluation\lib\site-packages\matplotlib\colorbar.py in __init__(self, ax, mappable, **kwargs)
   1195             if isinstance(mappable, martist.Artist):
   1196                 _add_disjoint_kwargs(kwargs, alpha=mappable.get_alpha())
-> 1197             super().__init__(ax, **kwargs)
   1198 
   1199         mappable.colorbar = self

~\Anaconda3\envs\data-evaluation\lib\site-packages\matplotlib\_api\deprecation.py in wrapper(*args, **kwargs)
    469                 "parameter will become keyword-only %(removal)s.",
    470                 name=name, obj_type=f"parameter of {func.__name__}()")
--> 471         return func(*args, **kwargs)
    472 
    473     return wrapper

TypeError: __init__() got an unexpected keyword argument 'location'

这是为什么?如果我使用:

colorbar = fig.colorbar(im, ax=ax, location='left')
colorbar.set_label('y label')

而不是divider,它似乎可以工作,但是轴和颜色条之间的填充没有我想要的那么小。

您引用的例子 没有 使用 location 参数给 colorbar:

colorbar = fig.colorbar(im, cax=cax)

那是因为您要求它在新轴上绘制颜色条,您已经使用语句 cax = divider.append_axes("left", size="5%", pad=0.05) 将其放置在左侧。您可以看到在抛出错误之前正在为颜色条生成一个空轴。

请记住,这样做会颠倒颜色条刻度和标签的位置:

您可以通过在 绘制颜色条后 添加以下内容来避免这种情况(因为颜色条将撤消更改):

cax.yaxis.tick_left()
cax.yaxis.set_label_position('left')