如何将水平matplotlib色条对象的标签准确定位在下方或上方的色条中心?

问题描述 投票:1回答:1

这是我从matplotlib sample examples借来的一些代码,略有修改,为具有正确放置标签的图像生成水平颜色条:

from matplotlib import colors
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(19680801)
cmap = "cool"

fig, axs = plt.subplots()

# Generate data with a range that varies from one plot to the next.
data = (1 / 10) * np.random.rand(10, 20) * 1e-6
image = axs.imshow(data, cmap=cmap)
axs.label_outer()

# Find the min and max of all colors for use in setting the color scale.
vmin = image.get_array().min()
vmax = image.get_array().max()
norm = colors.Normalize(vmin=vmin, vmax=vmax)

cbar = fig.colorbar(image, ax=axs, orientation='horizontal', fraction=.1)
cbar.ax.set_ylabel('$[M_\u2609 kpc^{{-2}}]$', position=(30,1), fontsize=20, rotation=0)


plt.show()

但这是我不想要的输出。

Figure1

我想要一个正好位于colorbar(下方或上方)中心的标签。在上面的代码中更改了给position的坐标后,似乎没有任何灵活性来确定标签的位置。在matplotlib色条的背景下有什么我不知道的东西吗?非常感谢您的帮助。

python image matplotlib axis-labels colorbar
1个回答
3
投票

轴标签(ylabel)设计为沿相应的轴放置。另一方面,标题通过设计定位在轴对象的中心。因此,不应使用set_ylabel,而应使用set_title

cbar.ax.set_title('$[M_\u2609 kpc^{{-2}}]$', fontsize=20)

enter image description here

有关图形不同部分的更多信息,请参阅this example "Anatomy of a Figure"

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.