0

I want to plot a circle on a grid in python. I just need python to show the grid with squared cells. I wrote the following code, but it shows the grid with NON-squared cells.

Can anyone tell me how to make the grid cells be squared ?

enter image description here

import matplotlib.pyplot as plt
import math

p=8

R=0.484*p

t=np.linspace(0, 2*np.pi)

x=R*np.cos(t)
y=R*np.sin(t)

plt.axis("equal")

plt.grid(True, which='both', axis='both')

plt.plot(x,y)
plt.show()
  • 1
    BTW for code block you just need to write \``` at the beginning and then \``` at the end completely. You don't need to do it every line – Nicolas Gervais Apr 12 '20 at 22:36
  • 1
    Note that the issue is `plt.axis("equal")`. Check my answer and the linked docs for more info – yatu Apr 12 '20 at 22:55

2 Answers2

2

Remove plt.axis("equal") and instead set plt.gca().set_aspect('equal'), which precisely sets the ratio of y-unit to x-unit of the axis scaling:

plt.grid(True, which='both', axis='both')
plt.plot(x,y)
plt.gca().set_aspect("equal")
plt.show()

Which would be the same as setting plt.axis('square').

Note that as mentioned in the docs, plt.axis("equal") is equal to setting plt.gca().set_aspect('equal', adjustable='datalim'), which will not produce the expected output, since data limits may not be respected in this case.

The above will give:

enter image description here

yatu
  • 86,083
  • 12
  • 84
  • 139
  • Thanks for your answer. It is correct. I am new in python. Could you please tell me how to put the coordinate origin at the center of the circle? @yatu – Mohammed Alhissi Apr 12 '20 at 23:04
  • 1
    It is right? (0,0) is in the center @MohammedAlhissi In any case, for a new question, I kindly encourage you to ask a new question here in SO. Otherwise the answers might mislead future readers – yatu Apr 12 '20 at 23:06
1

If you add this line after plt.grid() it will write all the x-ticks and the squares will be squared:

plt.xticks(range(-6, 6))

enter image description here

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143