MPL.pyplot - 如何重新定位水平颜色条的单位?
MPL.pyplot - How to relocate the units of a horizontal colorbar?
我正在尝试自定义绘图的外观,以便将其另存为图像。关于情节及其颜色条,我几乎已经准备好了一切。使用颜色条参数,我通过定义颜色条的轴使其水平放置并放置在主图的顶部。颜色条单位的默认位置设置在它的底部,我希望它们位于顶部以节省一些 space,但我找不到如何。这是我的代码:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
img = ax.imshow(data, cmap='gray', origin='lower')
# positioning colorbar
cax = fig.add_axes([0.2235, 0.93, 0.58, 0.03])
fig.colorbar(img, orientation='horizontal', cax=cax)
fig.savefig('map.png', bbox_inches='tight')
总而言之,颜色条的单位出现在颜色条和主图之间。我想将单位重新定位到颜色条的顶部(如果可能的话)。非常感谢任何帮助。
你只需要将ticklocation
传递给colorbar
:
fig.colorbar(img, orientation='horizontal', cax=cax, ticklocation='top')
如果您希望它更加交钥匙:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(constrained_layout=True)
img = ax.imshow(np.random.randn(30, 30), cmap='gray', origin='lower')
fig.colorbar(img, location='top', ax=ax, shrink=0.5)
plt.show()
我正在尝试自定义绘图的外观,以便将其另存为图像。关于情节及其颜色条,我几乎已经准备好了一切。使用颜色条参数,我通过定义颜色条的轴使其水平放置并放置在主图的顶部。颜色条单位的默认位置设置在它的底部,我希望它们位于顶部以节省一些 space,但我找不到如何。这是我的代码:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
img = ax.imshow(data, cmap='gray', origin='lower')
# positioning colorbar
cax = fig.add_axes([0.2235, 0.93, 0.58, 0.03])
fig.colorbar(img, orientation='horizontal', cax=cax)
fig.savefig('map.png', bbox_inches='tight')
总而言之,颜色条的单位出现在颜色条和主图之间。我想将单位重新定位到颜色条的顶部(如果可能的话)。非常感谢任何帮助。
你只需要将ticklocation
传递给colorbar
:
fig.colorbar(img, orientation='horizontal', cax=cax, ticklocation='top')
如果您希望它更加交钥匙:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(constrained_layout=True)
img = ax.imshow(np.random.randn(30, 30), cmap='gray', origin='lower')
fig.colorbar(img, location='top', ax=ax, shrink=0.5)
plt.show()