【问题标题】:MPL.pyplot - How to relocate the units of a horizontal colorbar?MPL.pyplot - 如何重新定位水平颜色条的单位?
【发布时间】:2023-03-29 18:08:01
【问题描述】:

我正在尝试自定义我的情节的外观,以便我可以将其保存为图像。关于情节及其颜色条,我已经准备好了一切。使用颜色条参数,我通过定义颜色条的轴使其水平并将其放置在主图的顶部。颜色栏单位的默认位置设置在它的底部,我希望它们位于顶部以节省一些空间,但我找不到如何。这是我的代码:

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')

总而言之,颜色条的单位出现在颜色条和主图之间。我想将单位重新定位到颜色栏的顶部(如果可能的话)。非常感谢任何帮助。

【问题讨论】:

    标签: python-3.x matplotlib colorbar


    【解决方案1】:

    您只需将ticklocation 传递给colorbar

    fig.colorbar(img, orientation='horizontal', cax=cax, ticklocation='top')
    

    【讨论】:

    • 是的!谢谢!!
    【解决方案2】:

    如果您希望它更全包:

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多