【问题标题】:colorbar positioning Matplotlib颜色条定位 Matplotlib
【发布时间】:2021-05-14 02:28:44
【问题描述】:

我已按照此线程 Seaborn Heatmap: Move colorbar on top of the plot 上关于在图形上定位颜色条的答案。

但是我想将颜色条缩小到默认值的 50%。如果我阅读 colorbar 函数的文档字符串,它表明我可以传递关键字参数“shrink”。

这是我编写的代码(其中 HM 是海洋热图):

from mpl_toolkits.axes_grid1.colorbar import colorbar

HM_divider = make_axes_locatable(HM)
# define size and padding of axes for colorbar
cax = HM_divider.append_axes('right', size = '5%', pad = '25%')
# make colorbar for heatmap. 
# Heatmap returns an axes obj but you need to get a mappable obj (get_children)
colorbar(HM.get_children()[0], cax = cax, orientation = 'vertical', shrink=0.5)

但是当我运行这个时,我得到一个 TypeError:TypeError: __init__() got an unexpected keyword argument 'shrink'

【问题讨论】:

  • this 会有所帮助。你运行的是什么版本的matplotlib
  • 嗨,杰。版本是 3.1.3
  • 不要使用 make_axes_locatable 或为此。使用 ax.inset_axes 并且不要使用收缩参数,只需将插入轴设置为您想要的大小。
  • 谢谢乔迪 - 了解该选项。但是我仍然很困惑为什么在这种情况下它不会采用收缩参数
  • 如果你写colorbar(),它来自哪个库?如果来自matplotlib.pyplot,请避免混淆,写成plt.colorbar()

标签: python matplotlib seaborn


【解决方案1】:

查看链接的帖子,我猜这是您尝试的步骤:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from mpl_toolkits.axes_grid1.colorbar import colorbar

df = pd.DataFrame(np.random.random((5,5)), columns=["a","b","c","d","e"])

HM = sns.heatmap(df, cbar = False)
HM_divider = make_axes_locatable(HM)
cax = HM_divider.append_axes('right', size = '5%', pad = '25%')
colorbar(HM.get_children()[0], cax = cax, orientation = 'vertical', shrink=0.5)

我得到同样的错误:

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

因为mpl_toolkits.axes_grid1.colorbar 没有收缩选项。它来自 cmets 中提出的 plt.colorbar。切换到这个可能会更好,因为mpl_toolkits.axes_grid1.colorbar module and its colorbar implementation are deprecated in favor of matplotlib.colorbar。所以应该是这样的:

fig,ax = plt.subplots()
sns.heatmap(df, cbar = False,ax=ax)
fig.colorbar(ax.get_children()[0],orientation = 'vertical', shrink=0.5)

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 2019-09-21
    • 2014-06-02
    • 2012-10-29
    • 2013-05-18
    • 1970-01-01
    • 2013-01-06
    相关资源
    最近更新 更多