Circle equation showing a circle

The following formula is used to classify points from two-dimensional space:

f(x1,x2) = np.sign(x1^2+x2^2-.6) 

All points are in the space X = [-1,1] x [-1,1] with a uniform probability of choosing each x.

Now I would like to visualize a circle that is equal to:

 0 = x1^2+x2^2-.6 

The x1 values ​​must be on the x axis and the x2 values ​​on the y axis.

It should be possible, but it's hard for me to convert the equation into a graph.

+8
python numpy matplotlib plot equation
source share
4 answers

You can use the contour plot as follows (based on examples at http://matplotlib.org/examples/pylab_examples/contour_demo.html ):

 import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1.0, 1.0, 100) y = np.linspace(-1.0, 1.0, 100) X, Y = np.meshgrid(x,y) F = X**2 + Y**2 - 0.6 plt.contour(X,Y,F,[0]) plt.show() 

This gives the following graph

enter image description here

Finally, some general statements:

  • x^2 doesn't mean what you think it does in python, you should use x**2 .
  • x1 and x2 terribly misleading (for me), especially if you state that x2 should be on the y axis.
  • (Thanks to Dux) You can add plt.gca().set_aspect('equal') so that the picture looks like a circle, making the axis equal.
+5
source share

The @BasJansen solution will certainly get you there, it is either very inefficient (if you use a lot of grid points) or inaccurate (if you use only a few grid points).

You can easily draw a circle directly. Given 0 = x1**2 + x**2 - 0.6 , it follows that x2 = sqrt(0.6 - x1**2) (as Dux pointed out).

But what you really want to do is convert your Cartesian coordinates to polar.

 x1 = r*cos(theta) x2 = r*sin(theta) 

if you use these permutations in a circular equation, you will see that r=sqrt(0.6) .

So now you can use this for your plot:

 import numpy as np import matplotlib.pyplot as plt # theta goes from 0 to 2pi theta = np.linspace(0, 2*np.pi, 100) # the radius of the circle r = np.sqrt(0.6) # compute x1 and x2 x1 = r*np.cos(theta) x2 = r*np.sin(theta) # create the figure fig, ax = plt.subplots(1) ax.plot(x1, x2) ax.set_aspect(1) plt.show() 

Result:

enter image description here

+6
source share

What about drawing x-values ​​and calculating the corresponding y-values?

 import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1, 1, 100, endpoint=True) y = np.sqrt(-x**2. + 0.6) plt.plot(x, y) plt.plot(x, -y) 

produces

enter image description here

This, obviously, can be done much nicer, but it is only for demonstration ...

+5
source share
 # x**2 + y**2 = r**2 r = 6 x = np.linspace(-r,r,1000) y = np.sqrt(-x**2+r**2) plt.plot(x, y,'b') plt.plot(x,-y,'b') plt.gca().set_aspect('equal') plt.show() 

gives:

enter image description here

0
source share

All Articles