Matplotlib 颜色条:__init__() 得到意外的关键字参数“location”

问题描述 投票:0回答:2

我试图按照此处给出的示例在轴左侧绘制一个 matplotlib 颜色条:https://matplotlib.org/stable/gallery/axes_grid1/simple_colorbar.html#sphx-glr-gallery-axes-grid1-简单-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
,它似乎可以工作,但是轴和颜色条之间的填充没有我想要的那么小。

python matplotlib plot colorbar
2个回答
2
投票

您引用的示例使用

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')


0
投票
对于此代码,我收到错误:

https://matplotlib.org/stable/gallery/subplots_axes_and_figures/gridspec_multicolumn.html#sphx-glr-gallery-subplots-axes-and-figures-gridspec-multicolumn-py

TypeError:

init()得到了意外的关键字参数“layout”

为什么?

© www.soinside.com 2019 - 2024. All rights reserved.