简体   繁体   English

Matplotlib:扩展轴以填充图形,x 和 y 的比例相同

[英]Matplotlib: Expanding axes to fill figure, same scale on x and y

I know 2 things but separately.我知道两件事,但分开。

figure.tight_layout 

will expand my current axes将扩展我当前的轴

axes.aspect('equal')

will keep same scale on x and y.将在 x 和 y 上保持相同的比例。

But when I use them both I get square axes view and I want it to be expanded.但是当我同时使用它们时,我会得到方轴视图,并且我希望它被扩展。 By keeping same scale I mean there is same distance from 0 to 1 on x and y axis.通过保持相同的比例,我的意思是在 x 和 y 轴上从 0 到 1 的距离相同。 Is there any way to make it happen?有没有办法让它发生? Keep same scale and expand to full figure(not only a square) The answer should work with autoscale保持相同的比例并扩展到全图(不仅是正方形)答案应该与自动缩放一起使用

There might be less clumsy way, but at least you can do it manually.可能有不那么笨拙的方法,但至少您可以手动完成。 A very simple example:一个非常简单的例子:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1],[1,0])
ax.set_aspect(1)
ax.set_xlim(0, 1.5)

creates创造

在此处输入图片说明

which honours the aspect ratio.它尊重纵横比。

If you want to have the automatic scaling offered by the tight_layout , then you'll have to do some maths of your own:如果你想拥有由tight_layout提供的自动缩放,那么你必须自己做一些数学计算:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1],[1,0])
fig.tight_layout()

# capture the axis positioning in pixels
bb = fig.transFigure.transform(ax.get_position())
x0, y0 = bb[0]
x1, y1 = bb[1]
width = x1 - x0
height = y1 - y0

# set the aspect ratio 
ax.set_aspect(1)

# calculate the aspect ratio of the plot
plot_aspect = width / height

# get the axis limits in data coordinates
ax0, ax1 = ax.get_xlim()
ay0, ay1 = ax.get_ylim()
awidth = ax1 - ax0
aheight = ay1 - ay0

# calculate the plot aspect
data_aspect = awidth / aheight

# check which one needs to be corrected
if data_aspect < plot_aspect:
    ax.set_xlim(ax0, ax0 + plot_aspect * aheight)
else:
    ax.set_ylim(ay0, ay0 + awidth / plot_aspect)

Of course, you may set the xlim and ylim any way you want, you might, for example, want to add an equal amount of space to either end of the scale.当然,您可以按您想要的任何方式设置xlimylim ,例如,您可能想要在比例尺的任一端添加等量的空间。

在此处输入图片说明

The solution that worked in my case was to call在我的情况下工作的解决方案是调用

axis.aspect("equal")
axis.set_adjustable("datalim")

stolen from this example in the documentation.从文档中的此示例中窃取。

示例图像

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

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