Is it possible to plot implicit equations using Matplotlib? Is it possible to plot implicit equations using Matplotlib? python python

Is it possible to plot implicit equations using Matplotlib?


Since you've tagged this question with sympy, I will give such an example.

From the documentation: http://docs.sympy.org/latest/modules/plotting.html.

from sympy import var, plot_implicitvar('x y')plot_implicit(x*y**3 - y*x**3)


I don't believe there's very good support for this, but you could try something like

import matplotlib.pyplotfrom numpy import arangefrom numpy import meshgriddelta = 0.025xrange = arange(-5.0, 20.0, delta)yrange = arange(-5.0, 20.0, delta)X, Y = meshgrid(xrange,yrange)# F is one side of the equation, G is the otherF = Y**XG = X**Ymatplotlib.pyplot.contour(X, Y, (F - G), [0])matplotlib.pyplot.show()

See the API docs for contour: if the fourth argument is a sequence then it specifies which contour lines to plot. But the plot will only be as good as the resolution of your ranges, and there are certain features it may never get right, often at self-intersection points.


matplotlib does not plot equations; it plots serieses of points. You can use a tool like scipy​.optimize to numerically calculate y points from x values (or vice versa) of implicit equations numerically or any number of other tools as appropriate.


For example, here is an example where I plot the implicit equation x ** 2 + x * y + y ** 2 = 10 in a certain region.

from functools import partialimport numpyimport scipy.optimizeimport matplotlib.pyplot as ppdef z(x, y):    return x ** 2 + x * y + y ** 2 - 10x_window = 0, 5y_window = 0, 5xs = []ys = []for x in numpy.linspace(*x_window, num=200):    try:        # A more efficient technique would use the last-found-y-value as a         # starting point        y = scipy.optimize.brentq(partial(z, x), *y_window)    except ValueError:        # Should we not be able to find a solution in this window.        pass    else:        xs.append(x)        ys.append(y)pp.plot(xs, ys)pp.xlim(*x_window)pp.ylim(*y_window)pp.show()