【matplotlib】colorbarの高さを図と揃える
目次
matplotlibでcolorbarの高さと図を揃える方法についてメモ。
Sponsored by Google AdSense
import matplotlib
import matplotlib.axes
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
f"{matplotlib.__version__=}"
"matplotlib.__version__='3.8.0'"
# 乱数発生用ジェネレータ
rng = np.random.default_rng(334)
fig, ax = plt.subplots(figsize=(3.0, 3.0), dpi=144)
ax: matplotlib.axes.Axes
mappable = ax.scatter(
rng.random(100), rng.random(100), c=rng.random(100), vmin=0, vmax=1
)
# layout
ax.set_xlim(-0.05, 1.05)
ax.set_ylim(-0.05, 1.05)
ax.set_aspect("equal", adjustable="box")
# ** 【本題】colorbar用の領域の切り出し **
divider = make_axes_locatable(ax)
cax = divider.append_axes(position="right", size="5%", pad="3%")
# ************************************
# caxの指定
fig.colorbar(mappable, cax=cax)
fig.tight_layout()
まとめ
from mpl_toolkits.axes_grid1 import make_axes_locatable
ax: matplotlib.axes.Axes
figure: matplotlib.figure.Figure
# colorbar用の領域の切り出し
divider = make_axes_locatable(ax)
cax = divider.append_axes(position="right", size="5%", pad="3%")
# caxの指定
fig.colorbar(mappable, cax=cax)