在sympy绘图中,如何获得具有固定纵横比的绘图?

2024-04-25 06:13:20 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我用这个片段画一个圆

from sympy import *
x, y = symbols('x y')        
p1 = plot_implicit(Eq(x**2 +y**2, 1),aspect_ratio=(1.,1.))

我要一个像这样的数字窗口

enter image description here

现在纵横比不是我所期望的,因为我看到的是椭圆而不是圆。此外,如果我改变窗口的纵横比(拖动窗口的右下角),也会改变绘图的纵横比。。。下图是我拖动角点以查看圆后得到的图像:

enter image description here

我想得到一个像你在Matlab中设置axis equal的图,当你画一个椭圆时,请看http://it.mathworks.com/help/matlab/creating_plots/aspect-ratio-for-2-d-axes.html

enter image description here

我错过了什么?在

我使用的是Jupyter,笔记本服务器的版本是4.1.0,运行于:Python 2.7.11 | Anaconda 2.5.0(64位)(默认值,2015年12月6日,18:08:32)[GCC 4.4.7 20120313(Red Hat 4.4.7-1)]


Tags: from图像import绘图plot数字eq椭圆
3条回答

现在,2019年9月,这一准则生效:

import matplotlib.pyplot as plt
import sympy

x, y = sympy.symbols('x y')

plt.ion() #interactive on 

p1 = sympy.plot_implicit(sympy.Eq(x**2 +y**2, 4), block = False)

fg, ax = p1._backend.fig, p1._backend.ax  # get matplotib's figure and axes

# Use matplotlib to change appearance:
ax.axis('tight')  # list of float or {‘on’, ‘off’, ‘equal’, ‘tight’, ‘scaled’, ‘normal’, ‘auto’, ‘image’, ‘square’}
ax.set_aspect("equal") # 'auto', 'equal' or a positive integer is allowed
ax.grid(True)
plt.ioff() #interactive off
plt.show()

我不确定Sympy的稳定API是否包含了这一点,但您可以提取matplotlib的figure和axis实例,并使用标准matplotlib调用来更改绘图的外观:

import matplotlib.pyplot as plt
import sympy as sy

x, y = sy.symbols('x y')
p1 = sy.plot_implicit(sy.Eq(x**2 +y**2, 4))
fg, ax = p1._backend.fig, p1._backend.ax  # get matplotib's figure and ax

# Use matplotlib to change appearance: 
ax.axis('tight')  # list of float or {‘on’, ‘off’, ‘equal’, ‘tight’, ‘scaled’, ‘normal’, ‘auto’, ‘image’, ‘square’}
ax.set_aspect("equal") # 'auto', 'equal' or a positive integer is allowed
ax.grid(True)
fg.canvas.draw()


plt.show()  # enter matplotlib's event loop (not needed in Jupyter)

这样可以得到: Tight Axis with equal aspect ratio

plot_implicit的帮助中,提到了x_var和{}-参数。使用它们可以手动设置x轴和y轴的限制。如果适当缩放这些限制,则可以获得均匀的纵横比。

from sympy import *

x, y = symbols('x y')

scal = 3840/2400 # corresponds to your screen resolution
a = 1.05

p1 = plot_implicit(Eq(x**2+y**2,1),title='with xlim and ylim\n',\
                   xlim=(-1,1), ylim=(-1,1),aspect_ratio='equal')

p2 = plot_implicit(Eq(x**2+y**2,1),title='with x_var and y_var\n',\
                   x_var=(x,-a*scal,a*scal), y_var=(y,-a,a))

(我的交响乐版本:1.1.1)

相关问题 更多 >