如何在Python matplotlib中使x轴和y轴的比例相等?

问题:如何在Python matplotlib中使x轴和y轴的比例相等?

我希望在方形图上画线。

天秤x-axisy-axis应该是相同的。

例如x的范围是0到10,在屏幕上是10厘米。y也必须在0到10的范围内,并且也必须是10 cm。

即使我迷失了窗口大小,也必须保持正方形。

目前,我的图形与窗口大小一起缩放。

我该如何实现?

更新:

我尝试了以下操作,但没有成功。

plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.axis('equal')

I wish to draw lines on a square graph.

The scales of x-axis and y-axis should be the same.

e.g. x ranges from 0 to 10 and it is 10cm on the screen. y has to also range from 0 to 10 and has to be also 10 cm.

The square shape has to be maintained, even if I mess around with the window size.

Currently, my graph scales together with the window size.

How may I achieve this?

UPDATE:

I tried the following, but it did not work.

plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.axis('equal')

回答 0

您需要对api进行更深入的研究:

from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()

set_aspect的文档

You need to dig a bit deeper into the api to do this:

from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()

doc for set_aspect


回答 1

plt.axis('scaled')

对我来说效果很好。

plt.axis('scaled')

works well for me.


回答 2

尝试类似的方法:

import pylab as p
p.plot(x,y)
p.axis('equal')
p.show()

Try something like:

import pylab as p
p.plot(x,y)
p.axis('equal')
p.show()

回答 3

文档plt.axis()。这个:

plt.axis('equal')

不起作用,因为它更改了轴的界限以使圆看起来是圆形。您想要的是:

plt.axis('square')

这将创建具有相等轴的正方形图。

See the documentation on plt.axis(). This:

plt.axis('equal')

doesn’t work because it changes the limits of the axis to make circles appear circular. What you want is:

plt.axis('square')

This creates a square plot with equal axes.