Python Matplotlib:获取和设置轴位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23137991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:19:16  来源:igfitidea点击:

Matplotlib: get and set axes position

pythonmatplotlibaxessubplot

提问by ?smund

In matlab, it's straightforward to get and set the position of an existing axes on the figure:

在 matlab 中,获取和设置图中现有轴的位置很简单:

  pos = get(gca(), 'position')
  set(gca(), 'position', pos)

How do I do this in Matplotlib?

我如何在 Matplotlib 中做到这一点?

I need this for two related reasons:

我需要这个有两个相关的原因:

These are the specific problems I'm trying to solve:

这些是我试图解决的具体问题:

  • I have a column of subplots where some have colorbars and some don't, and they aren't the same width i.e. the X axises don't align. The colorbar steals space from the axes. This also happens in matlab, and there I'd use the above trick to make all the axes equally wide by copying the width from an axes with a colorbar to those without.

  • add space between individual subplots by shrinkin an axes. The adjust_subplots() function adjusts all subplots the same.

  • 我有一列子图,其中有些有颜色条,有些没有,而且它们的宽度不同,即 X 轴不对齐。颜色条从轴上窃取空间。这也发生在 matlab 中,我会使用上述技巧通过将宽度从带有颜色条的轴复制到没有颜色条的轴来使所有轴的宽度相同。

  • 通过收缩轴在各个子图之间添加空间。该 adjust_subplots() 函数调整所有子图相同。

采纳答案by Molly

Setting axes position is similar in Matplotlib. You can use the get_position and set_position methods of the axes.

在 Matplotlib 中设置轴位置类似。您可以使用的 get_position 和 set_position 方法

import matplotlib.pyplot as plt

ax = plt.subplot(111)
pos1 = ax.get_position() # get the original position 
pos2 = [pos1.x0 + 0.3, pos1.y0 + 0.3,  pos1.width / 2.0, pos1.height / 2.0] 
ax.set_position(pos2) # set a new position

You might also want to take a look at GridSpecif you haven't already.

如果您还没有,您可能还想看看GridSpec