Sympy and plotting

2019-07-14 06:33发布

I have a few questions about what how to work with graphics, using Sympy.

My code:

from sympy import *
x, y = symbols("x y")
plot_implicit(Eq(x**2 + y**2, 4), (x, -3, 3), (y, -3, 3))

1) The graph is obtained stretched along the x axis.

enter image description here

How to make so that the curve looked like a circle?

2) How to add other elements to the chart. For example, the point O(0, 0) and the line y = x.

enter image description here

1条回答
Emotional °昔
2楼-- · 2019-07-14 06:50

According to the docstring of plot.py, you can get the backend wrapper of the Matplotlib axes and figure that SymPy uses, through _backend attribute, and then modify properties as any other Matplotlib objects. Check this example:

import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook
from sympy import *

x, y = symbols("x y")
hp = plot_implicit(Eq(x**2 + y**2, 4), (x, -3, 3), (y, -3, 3))
fig = hp._backend.fig
ax = hp._backend.ax
xx = yy = np.linspace(-3,3)
ax.plot(xx,yy) # y = x
ax.plot([0],[0],'o') # Point (0,0)
ax.set_aspect('equal','datalim')
fig.canvas.draw()

The Sympy Plot objects have append and extend methods that allows add a Plot object to other, but this don't work (at least for me and using Jupyter).

Another option is use only Matplotlib:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1,1)
xx,yy = np.linspace(-3,3), np.linspace(-3,3)
x,y = np.meshgrid(xx,yy)
ax.contour(x, y, (x**2+y**2-4), [0]);
ax.plot([0],[0],"o")
ax.plot(xx,yy)
ax.set_aspect('equal','datalim')
查看更多
登录 后发表回答