简体   繁体   English

如何在不改变图形大小的情况下将轴框架定位在图形内? [Python,matplotlib]

[英]How do I position the axis frame inside a figure without changing the size of the figure? [Python, matplotlib]

I'm trying to create a video of many figures, so I need the axis to remain steady across multiple, independent figures.我正在尝试创建一个包含许多图形的视频,因此我需要轴在多个独立图形中保持稳定。 However, the y-axis changes scale, so the framing of the axis keeps moving as the ticklabels change.但是,y 轴会改变比例,因此轴的框架会随着刻度标签的变化而不断移动。 I'm trying to manually tell matplotlib exactly what size the whole figure should be and tell it exactly the position of the axis within the figure, but it's not working properly.我试图手动告诉 matplotlib 整个图形应该是什么大小,并准确地告诉它图形中轴的位置,但它不能正常工作。

Here's what a base figure looks like:下面是基数的样子:

import matplotlib.pyplot as plt

fig=plt.figure(figsize=(8,4),facecolor=(0.5,0.5,0.5))
ax=fig.add_subplot()
ax.plot([5,10],[800,900])
plt.show()

在此处输入图片说明

Here is one way for how I'm trying to change it if I want the axis frame to start at left=0.5, bottom=0.5, width=0.2, and height=0.2.如果我希望轴框架从左 = 0.5、底部 = 0.5、宽度 = 0.2 和高度 = 0.2 开始,这是我尝试更改它的一种方法。 I've tried many different ways, and all have failed, so this is illustrative of what I'm trying to do:我尝试了很多不同的方法,但都失败了,所以这说明了我正在尝试做的事情:

fig=plt.figure(figsize=(8,4),facecolor=(0.5,0.5,0.5))
ax=fig.add_axes((0.5,0.5,0.2,0.2))
ax.plot([5,10],[800,900])
plt.show()

在此处输入图片说明

Now, I want it to look more like this so that the black box of the axis frame will be in the exact same position for every figure, and each figure will be the exact same size.现在,我希望它看起来更像这样,以便每个图形的轴框架的黑框都处于完全相同的位置,并且每个图形的大小都完全相同。 That way, when I make it an animation, the black frame won't be jerking around.这样,当我将其制作成动画时,黑框就不会晃动了。 (Obviously, I wouldn't make the buffer that big in the real video.) (显然,我不会在真实视频中制作那么大的缓冲区。)

在此处输入图片说明

You need to use ax.set_position .您需要使用ax.set_position

If your ax box initially occupies the full figure, you can create a new size relatively to the old one, for example:如果您的斧头盒最初占据了整个数字,则可以相对于旧尺寸创建一个新尺寸,例如:

import matplotlib.pyplot as plt 

fig = plt.figure(figsize=(8, 4), facecolor=(0.5, 0.5, 0.5))
ax = fig.add_subplot(111)
bbox = ax.get_position()
new_bbox = (bbox.x0+0.40, bbox.y0+0.40, bbox.width*0.5, bbox.height*0.5)
ax.set_position(new_bbox)
ax.plot([5, 10], [800, 900])
plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM