I have encountered some problem while I was drawing a direction of arrow. I have point (x,y) coordinates and angle of them. What I want to do is that to draw arrow according to the given angle (just to show the point direction as an arrow in each point coordinate). Here, we should assume coordinates of '+x', '+y', '-x ', '-y' are 90, 0, 270, 180 degrees, respectively.
I am a bit unfamiliar with Python drawing tools. I am still not sure to draw directional point (arrow based on angle) whether I use pylab or some other modules or.. still not sure at all. I put the following codes as a sample to give better description:
# Inputs:
x = np.array([ 2, 4, 8, 10, 12, 14, 16])
y = np.array([ 5, 10, 15, 20, 25, 30, 35])
angles = np.array([45,275,190,100,280,18,45])
import numpy as np
import scipy as sp
import pylab as pl
def draw_line(x,y,angle):
# First, draw (x,y) coordinate ???
# Second, according to the angle indicate the direction as an arrow ???
You can draw arrows with matplotlib.pyplot.arrow(x, y, dx, dy, hold=None, **kwargs)
. The part you seem to have difficulty with is defining the offsets dx
and dy
given an angle and an arrow length r
. For polar coordinates with angle
in radians
dx = r*cos(angle)
dy = r*sin(angle)
so that your draw_line
function becomes
def draw_line(x, y, angle):
r = 1 # or whatever fits you
arrow(x, y, r*cos(angle), r*sin(angle))
This will draw an arrow starting at (x,y)
in the direction of angle
with a length of 1
.
Your designated angles follow map conventions, whereas the Cartesian conventions have (+x, +y, -x, -y) as (0, 90, 180, 270) respectively. They will also take radians. To convert your angles:
import math
cartesianAngleRadians = (450-mapAngleDegrees)*math.pi/180.0
Here's source code that draws tick marks according to your provided x,y points.
import numpy as np
import scipy as sp
import pylab as pl
import math
x = np.array([ 2, 4, 8, 10, 12, 14, 16])
y = np.array([ 5, 10, 15, 20, 25, 30, 35])
angles = np.array([45,275,190,100,280,18,45])
def draw_line(x,y,angle,length):
cartesianAngleRadians = (450-angle)*math.pi/180.0
terminus_x = x + length * math.cos(cartesianAngleRadians)
terminus_y = y + length * math.sin(cartesianAngleRadians)
pl.plot([x, terminus_x],[y,terminus_y])
print [x, terminus_x],[y,terminus_y]
pl.axis('equal')
pl.axis([-5,20,-5,40])
for i in range(0,len(x)):
print x[i],y[i],angles[i]
draw_line(x[i],y[i],angles[i],1)
pl.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With