Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enforce a square grid in matplotlib

Using matplotlib.pyplot I need to draw basic 2D vector space diagrams and I need the x-axis and the y-axis units to be visually equal in length (1 to 1) so that each grid unit looks square (not squashed, not elongated). To be clear, I don't need or want a square graph, but I need the units to look square at all times no matter the graph aspect ratio or length of either axis.

I've tried using axis('equal') and this doesn't work. Note that I'm working in in Jupyter notebook, which seems to want to limit the height of the scale. (This may have some interfering limit on pyplot? I don't know). I've been wrestling with this for several hours and am not finding anything that works.

def plot_vector2d(vector2d, origin=[0, 0], **options):
    return plt.arrow(origin[0], origin[1], vector2d[0], vector2d[1],
          head_width=0.2, head_length=0.3, length_includes_head=True,
          width=0.02, 
          **options)

plot_vector2d([1,0], color='g')
plot_vector2d([0,1], color='g')

plot_vector2d([2,10], color='r')
plot_vector2d([3,1], color='r')

plt.axis([-3, 6, -2, 11], 'equal')
plt.xticks(np.arange(-3, 7, 1))
plt.yticks(np.arange(-2, 11, 1))
plt.grid()
plt.show()

See how the vertical axis is squashed compared to the horizontal. axis('equal') seems to have no effect.

See how the vertical axis is squashed compared to the horizontal. axis('equal') seems to have no effect.

like image 528
Richard Walker Avatar asked May 03 '18 15:05

Richard Walker


1 Answers

You need to set the aspect ratio of your axis to "equal". You can do this using set_aspect. The documentation states:

‘equal’ same scaling from data to plot units for x and y

Your code then becomes:

def plot_vector2d(vector2d, origin=[0, 0], **options):
    return plt.arrow(origin[0], origin[1], vector2d[0], vector2d[1],
          head_width=0.2, head_length=0.3, length_includes_head=True,
          width=0.02, 
          **options)

plot_vector2d([1,0], color='g')
plot_vector2d([0,1], color='g')

plot_vector2d([2,10], color='r')
plot_vector2d([3,1], color='r')

plt.axis([-3, 6, -2, 11], 'equal')
plt.grid()
plt.gca().set_aspect("equal")

plt.show()

Which gives:

enter image description here

like image 105
DavidG Avatar answered Sep 21 '22 00:09

DavidG