【问题标题】:How to position the label of a horizontal matplotlib colorbar object exactly at the center of the colorbar below or above?如何将水平 matplotlib 颜色条对象的标签准确定位在颜色条下方或上方的中心?
【发布时间】:2018-09-11 06:19:10
【问题描述】:

这是我从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()

但这是我不想要的输出。

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

【问题讨论】:

  • 请提交一个可重现的最小示例:一小段代码可以重现您的问题,但完全独立。还要考虑准则here

标签: python image matplotlib axis-labels colorbar


【解决方案1】:

轴标签 (ylabel) 设计为沿相应轴放置。另一方面,根据设计,title 位于轴对象的中心。因此,您应该使用set_title,而不是使用set_ylabel

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

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

【讨论】:

    猜你喜欢
    • 2015-03-21
    • 2021-05-14
    • 2016-11-24
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    相关资源
    最近更新 更多