Shrink/adjust 图中的颜色条

Shrink/adjust the colorbar inside the plot

我正在尝试缩小位于地块内的 colorbar。当我把它放在情节之外时(即 pad=0.05),它工作得很好。 这是 MWE:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

z = np.random.random((10,10))

fig, ax = plt.subplots()
ima = ax.matshow(z)
divider = make_axes_locatable(ax)
cb = fig.colorbar(ima,  cax=divider.append_axes('right', size="4%", pad=-0.5),shrink=0.75,fraction=0.75)

plt.show()

我已经尝试了 shrinkfraction,但其中 none 似乎可以解决问题。我正在附上输出。非常感谢任何帮助!

您的基本问题是,如果您指定 cax,收缩和分数将不起作用;它只是填充您指定的轴。

我会用 inset_axes 来做到这一点,您应该在其中调整定位以获得您想要的东西:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

z = np.random.random((10,10))

fig, ax = plt.subplots()
ima = ax.matshow(z)
divider = make_axes_locatable(ax)
cb = fig.colorbar(ima,  cax=ax.inset_axes((0.9, 0.125, 0.05, 0.75)))

plt.show()