具有 AxesDivider 的顏色條#

axes_divider.make_axes_locatable 函數會取得現有的 Axes,將其新增至新的 AxesDivider,並傳回 AxesDividerappend_axes AxesDivider 的方法可用於在原始 Axes 的給定邊(「上」、「右」、「下」或「左」)上建立新的 Axes。此範例使用 append_axes 在 Axes 旁邊新增顏色條。

使用者應考慮直接將主要的 Axes 傳遞給 colorbar 的 *ax* 關鍵字引數,而不是像這樣手動建立可定位的 Axes。請參閱 放置顏色條

demo colorbar with axes divider
import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable

fig, (ax1, ax2) = plt.subplots(1, 2)
fig.subplots_adjust(wspace=0.5)

im1 = ax1.imshow([[1, 2], [3, 4]])
ax1_divider = make_axes_locatable(ax1)
# Add an Axes to the right of the main Axes.
cax1 = ax1_divider.append_axes("right", size="7%", pad="2%")
cb1 = fig.colorbar(im1, cax=cax1)

im2 = ax2.imshow([[1, 2], [3, 4]])
ax2_divider = make_axes_locatable(ax2)
# Add an Axes above the main Axes.
cax2 = ax2_divider.append_axes("top", size="7%", pad="2%")
cb2 = fig.colorbar(im2, cax=cax2, orientation="horizontal")
# Change tick position to top (with the default tick position "bottom", ticks
# overlap the image).
cax2.xaxis.set_ticks_position("top")

plt.show()

由 Sphinx-Gallery 產生的圖庫