Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to plot perpendicular vectors in Python

I would like to simply plot perpendicular vectors in 2D. I've implemented 2 ways to plot them in the code below but the vectors don't "look" perpendicular to me when the plots are drawn. If it makes any difference I'm using Spyder.

import numpy as np
import matplotlib.pyplot as plt
x1=[0,0,4,3]
x2=[0,0,-3,4]
x3=[0,0,3,-4]
soa =np.array([x1,x2,x3]) 
X,Y,U,V = zip(*soa) 
plt.figure()
ax = plt.gca()
ax.quiver(X,Y,U,V,angles='xy',scale_units='xy',scale=1)
ax.set_xlim([-10,10])
ax.set_ylim([-10,10])
plt.draw()
plt.show()

import pylab as pl
from matplotlib import collections  as mc
lines = [[(0, 1), (4, 3)], [(-3, 4), (3, -4)]]
c = np.array([(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1)])
lc = mc.LineCollection(lines, colors=c, linewidths=2)
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
like image 692
Fred Flores Avatar asked Dec 17 '16 19:12

Fred Flores


1 Answers

Your problem is that the size of the unit differs on the x and y axes. You need to force them to be equal.

In matplotlib.pyplot, add the line

plt.axes().set_aspect('equal')

just before you show the graph with

plt.show()

I get this result in the IPython console in Spyder:

enter image description here

In pylab, add the line

ax.set_aspect('equal')

at the end. However, these line segments still do not look perpendicular, and that is because they really are not perpendicular. The slope of your first, red line segment is 2/3, so your second, green line segment should have slope -3/2 but it actually has slope -4/3. Perhaps change your line to

lines = [[(0, 1), (4, 3)], [(-3, 4), (3, -5)]]

(I changed the ending -4 to -5) to get the correct second slope. You get a change from this first figure to the second:

enter image description here

enter image description here

and that last does look perpendicular.

like image 161
Rory Daulton Avatar answered Sep 24 '22 14:09

Rory Daulton