本篇内容主要讲解“怎么使用Python修改matplotlib.pyplot.colorbar的位置以对齐主图”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么使用Python修改matplotlib.pyplot.colorbar的位置以对齐主图”吧!
问题描述

像这样的图,我想把右边的colorbar设置成和主图一样高度
方法 0. plt.colorbar参数介绍
1. plt.colorbar(im, fraction=0.046, pad=0.04, shrink=1.0)
fraction可以从0.035-0.046调节以找到合适大小
但当图像的长、高对比过大时,可能不起作用
2. make_axes_locatable
这是matplotlib包里的一个函数
from mpl_toolkits.axes_grid1 import make_axes_locatable
im = plt.imshow(data)
divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", size="5%", pad="3%")
plt.colorbar(im, cax=cax)不适用于有投影参数的axe(会报错),如cartopy的GeoAxes
3. make_axes_locatables 升级版
import matplotlib.pyplot as plt
from mpl_toolkits import axes_grid1
def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs):
"""Add a vertical color bar to an image plot."""
divider = axes_grid1.make_axes_locatable(im.axes)
width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect)
pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
current_ax = plt.gca()
cax = divider.append_axes("right", size=width, pad=pad)
plt.sca(current_ax)
return im.axes.figure.colorbar(im, cax=cax, **kwargs)用法示例
im = plt.imshow(np.arange(200).reshape((20, 10)))
add_colorbar(im)
4. 手动给colorbar添加一个axe
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax = plt.axes()
im = ax.imshow(np.arange(100).reshape((10,10)))
# Create an axes for colorbar. The position of the axes is calculated based on the position of ax.
# You can change 0.01 to adjust the distance between the main image and the colorbar.
# You can change 0.02 to adjust the width of the colorbar.
# This practice is universal for both subplots and GeoAxes.
cax = fig.add_axes([ax.get_position().x1+0.01,ax.get_position().y0,0.02,ax.get_position().height])
plt.colorbar(im, cax=cax) # Similar to fig.colorbar(im, cax = cax)
效果展示

到此,相信大家对“怎么使用Python修改matplotlib.pyplot.colorbar的位置以对齐主图”有了更深的了解,不妨来实际操作一番吧!这里是天达云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!