颜色栏定位Matplotlib

2024-04-29 15:46:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经遵循了这个线程Seaborn Heatmap: Move colorbar on top of the plot中关于在图形上定位颜色条的答案

但是,我想将颜色栏缩小到默认值的50%。如果我读取colorbar函数的docstring,它建议我可以传递关键字参数“shrink”

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

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'


Tags: ofanobjforsizegetmake颜色
1条回答
网友
1楼 · 发布于 2024-04-29 15:46:36

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

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没有收缩选项。它来自于评论中提出的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)

enter image description here

相关问题 更多 >