Python – Plotting a circle with matplotlib

Plotting a circle with matplotlib library in python is an interesting task. If you google it, you will find quite good answers, but anyway, I am here because I want to summarize my point of view.

Pretty much, the idea is that about 100 points of a given reasonable diameter look like a circle, if these are distributed correctly in the coordinate system. How do we distribute these?

Well, let’s start with the bare minimum – 3 points per half to get this:

It is obvious that all the vertices of a square lie on a circle. Wow!

It is obvious, that our pairs are these ones – (x, y) = (-10, 0), (0, 10), (10, 0). How are these generated? For the x , we are using np.linespace and for y  it is (-x ^ 2 + r ^ 2)^2. Because we have -x in the y  equation, the length of x  and y is the same. Play a bit and see what happens with 5 points per size:

Almost a wheel!

 

The red part is the result of what is printed and the green part is the red part with negative y, so it looks like a mirrored image (if the mirror is the x-line). Pretty much that is all. If you want to see the beautiful circle, here it comes:

That’s what I am talking about!

The code looks like this:

If you are wondering what plt.gca().set_aspect(1), does it actually makes sure that your circle is not an ellipse, by forcing Jupyter Notebook to equalize the length of the distance between the numbers of the x and y axis. See how it would look without it, to get what I mean here.

Enjoy it!

Tagged with: , , , , ,