I am fairly new to using matplotlib and cannot find any examples that show two lines with the angle between them plotted.
This is my current image:
And this is an example of what I want to achieve:
I usually take a look at the Matplotlib gallery to get an idea of how to perform certain tasks but there does not seem to be anything similar.
You could use matplotlib.patches.Arc to plot an arc of the corresponding angle measure.
To draw the angle arc:
Define a function that could take 2 matplotlib.lines.Line2D objects, calculate the angle and return a matplotlib.patches.Arc object, which you can add to your plot along with the lines.
def get_angle_plot(line1, line2, offset = 1, color = None, origin = [0,0], len_x_axis = 1, len_y_axis = 1):
l1xy = line1.get_xydata()
# Angle between line1 and x-axis
slope1 = (l1xy[1][1] - l1xy[0][2]) / float(l1xy[1][0] - l1xy[0][0])
angle1 = abs(math.degrees(math.atan(slope1))) # Taking only the positive angle
l2xy = line2.get_xydata()
# Angle between line2 and x-axis
slope2 = (l2xy[1][3] - l2xy[0][4]) / float(l2xy[1][0] - l2xy[0][0])
angle2 = abs(math.degrees(math.atan(slope2)))
theta1 = min(angle1, angle2)
theta2 = max(angle1, angle2)
angle = theta2 - theta1
if color is None:
color = line1.get_color() # Uses the color of line 1 if color parameter is not passed.
return Arc(origin, len_x_axis*offset, len_y_axis*offset, 0, theta1, theta2, color=color, label = str(angle)+u"\u00b0")
To print the angle values :
Incase you want the angle value to be displayed inline, refer this SO Question for how to print inline labels in matplotlib. Note that you must print the label for the arc.
I made a small function which extracts the vertices of the arc and tries to compute the coordinate of the angle text.
This may not be optimal and may not work well with all angle values.
def get_angle_text(angle_plot):
angle = angle_plot.get_label()[:-1] # Excluding the degree symbol
angle = "%0.2f"%float(angle)+u"\u00b0" # Display angle upto 2 decimal places
# Get the vertices of the angle arc
vertices = angle_plot.get_verts()
# Get the midpoint of the arc extremes
x_width = (vertices[0][0] + vertices[-1][0]) / 2.0
y_width = (vertices[0][5] + vertices[-1][6]) / 2.0
#print x_width, y_width
separation_radius = max(x_width/2.0, y_width/2.0)
return [ x_width + separation_radius, y_width + separation_radius, angle]
Or you could always precompute the label point manually and use text to display the angle value. You can get the angle value from the label of the Arc object using the get_label() method (Since we had set the label to the angle value + the unicode degree symbol).
Example usage of the above functions :
fig = plt.figure()
line_1 = Line2D([0,1], [0,4], linewidth=1, linestyle = "-", color="green")
line_2 = Line2D([0,4.5], [0,3], linewidth=1, linestyle = "-", color="red")
ax = fig.add_subplot(1,1,1)
ax.add_line(line_1)
ax.add_line(line_2)
angle_plot = get_angle_plot(line_1, line_2, 1)
angle_text = get_angle_text(angle_plot)
# Gets the arguments to be passed to ax.text as a list to display the angle value besides the arc
ax.add_patch(angle_plot) # To display the angle arc
ax.text(*angle_text) # To display the angle value
ax.set_xlim(0,7)
ax.set_ylim(0,5)
If you do not care about inline placement of the angle text. You could use plt.legend() to print the angle value.
Finally :
plt.legend()
plt.show()
The offset parameter in the function get_angle_plot is used to specify a psudo-radius value to the arc.
This will be useful when angle arcs may overlap with each other.
( In this figure, like I said, my get_angle_text function is not very optimal in placing the text value, but should give you an idea on how to compute the point )
Adding a third line :
line_3 = Line2D([0,7], [0,1], linewidth=1, linestyle = "-", color="brown")
ax.add_line(line_3)
angle_plot = get_angle_plot(line_1, line_3, 2, color="red") # Second angle arc will be red in color
angle_text = get_angle_text(angle_plot)
ax.add_patch(angle_plot) # To display the 2nd angle arc
ax.text(*angle_text) # To display the 2nd angle value
Taking idea from #user3197452 here is what I use. This version combines text and also takes care of in-proportional axis ratios.
def add_corner_arc(ax, line, radius=.7, color=None, text=None, text_radius=.5, text_rotatation=0, **kwargs):
''' display an arc for p0p1p2 angle
Inputs:
ax - axis to add arc to
line - MATPLOTLIB line consisting of 3 points of the corner
radius - radius to add arc
color - color of the arc
text - text to show on corner
text_radius - radius to add text
text_rotatation - extra rotation for text
kwargs - other arguments to pass to Arc
'''
lxy = line.get_xydata()
if len(lxy) < 3:
raise ValueError('at least 3 points in line must be available')
p0 = lxy[0]
p1 = lxy[1]
p2 = lxy[2]
width = np.ptp([p0[0], p1[0], p2[0]])
height = np.ptp([p0[1], p1[1], p2[1]])
n = np.array([width, height]) * 1.0
p0_ = (p0 - p1) / n
p1_ = (p1 - p1)
p2_ = (p2 - p1) / n
theta0 = -get_angle(p0_, p1_)
theta1 = -get_angle(p2_, p1_)
if color is None:
# Uses the color line if color parameter is not passed.
color = line.get_color()
arc = ax.add_patch(Arc(p1, width * radius, height * radius, 0, theta0, theta1, color=color, **kwargs))
if text:
v = p2_ / np.linalg.norm(p2_)
if theta0 < 0:
theta0 = theta0 + 360
if theta1 < 0:
theta1 = theta1 + 360
theta = (theta0 - theta1) / 2 + text_rotatation
pt = np.dot(rotation_transform(theta), v[:,None]).T * n * text_radius
pt = pt + p1
pt = pt.squeeze()
ax.text(pt[0], pt[1], text,
horizontalalignment='left',
verticalalignment='top',)
return arc
get_angle function is what I have posted here, but copied again for completeness.
def get_angle(p0, p1=np.array([0,0]), p2=None):
''' compute angle (in degrees) for p0p1p2 corner
Inputs:
p0,p1,p2 - points in the form of [x,y]
'''
if p2 is None:
p2 = p1 + np.array([1, 0])
v0 = np.array(p0) - np.array(p1)
v1 = np.array(p2) - np.array(p1)
angle = np.math.atan2(np.linalg.det([v0,v1]),np.dot(v0,v1))
return np.degrees(angle)
def rotation_transform(theta):
''' rotation matrix given theta
Inputs:
theta - theta (in degrees)
'''
theta = np.radians(theta)
A = [[np.math.cos(theta), -np.math.sin(theta)],
[np.math.sin(theta), np.math.cos(theta)]]
return np.array(A)
To use it one can do this:
ax = gca()
line, = ax.plot([0, 0, 2], [-1, 0, 0], 'ro-', lw=2)
add_corner_arc(ax, line, text=u'%d\u00b0' % 90)
I've written a function to create a matplotlib Arc object that takes several helpful arguments. It also works on lines that do not intersect at the origin. For a given set of two lines, there are many possible arcs that the user may want to draw. This function lets one specify which one using the arguments. The text is drawn at the midpoint between the arc and the origin. Improvements are more than welcome in the comments, or on the gist containing this function.
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
Arc = matplotlib.patches.Arc
def halfangle(a, b):
"Gets the middle angle between a and b, when increasing from a to b"
if b < a:
b += 360
return (a + b)/2 % 360
def get_arc_patch(lines, radius=None, flip=False, obtuse=False, reverse=False, dec=0, fontsize=8):
"""For two sets of two points, create a matplotlib Arc patch drawing
an arc between the two lines.
lines: list of lines, of shape [[(x0, y0), (x1, y1)], [(x0, y0), (x1, y1)]]
radius: None, float or tuple of floats. If None, is set to half the length
of the shortest line
orgio: If True, draws the arc around the point (0,0). If False, estimates
the intersection of the lines and uses that point.
flip: If True, flips the arc to the opposite side by 180 degrees
obtuse: If True, uses the other set of angles. Often used with reverse=True.
reverse: If True, reverses the two angles so that the arc is drawn
"the opposite way around the circle"
dec: The number of decimals to round to
fontsize: fontsize of the angle label
"""
import numpy as np
from matplotlib.patches import Arc
linedata = [np.array(line.T) for line in lines]
scales = [np.diff(line).T[0] for line in linedata]
scales = [s[1] / s[0] for s in scales]
# Get angle to horizontal
angles = np.array([np.rad2deg(np.arctan(s/1)) for s in scales])
if obtuse:
angles[1] = angles[1] + 180
if flip:
angles += 180
if reverse:
angles = angles[::-1]
angle = abs(angles[1]-angles[0])
if radius is None:
lengths = np.linalg.norm(lines, axis=(0,1))
radius = min(lengths)/2
# Solve the point of intersection between the lines:
t, s = np.linalg.solve(np.array([line1[1]-line1[0], line2[0]-line2[1]]).T, line2[0]-line1[0])
intersection = np.array((1-t)*line1[0] + t*line1[1])
# Check if radius is a single value or a tuple
try:
r1, r2 = radius
except:
r1 = r2 = radius
arc = Arc(intersection, 2*r1, 2*r2, theta1=angles[1], theta2=angles[0])
half = halfangle(*angles[::-1])
sin = np.sin(np.deg2rad(half))
cos = np.cos(np.deg2rad(half))
r = r1*r2/(r1**2*sin**2+r2**2*cos**2)**0.5
xy = np.array((r*cos, r*sin))
xy = intersection + xy/2
textangle = half if half > 270 or half < 90 else 180 + half
textkwargs = {
'x':xy[0],
'y':xy[1],
's':str(round(angle, dec)) + "°",
'ha':'center',
'va':'center',
'fontsize':fontsize,
'rotation':textangle
}
return arc, textkwargs
It creates arcs like in the following image, using the attached script:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Arc
# lines are formatted like this: [(x0, y0), (x1, y1)]
line1 = np.array([(1,-2), (3,2)])
line2 = np.array([(2,2), (2,-2)])
lines = [line1, line2]
fig, AX = plt.subplots(nrows=2, ncols=2)
for ax in AX.flatten():
for line in lines:
x,y = line.T
ax.plot(x,y)
ax.axis('equal')
ax1, ax2, ax3, ax4 = AX.flatten()
arc, angle_text = get_arc_patch(lines)
ax1.add_artist(arc)
ax1.set(title='Default')
ax1.text(**angle_text)
arc, angle_text = get_arc_patch(lines, flip=True)
ax2.add_artist(arc)
ax2.set(title='flip=True')
ax2.text(**angle_text)
arc, angle_text = get_arc_patch(lines, obtuse=True, reverse=True)
ax3.add_artist(arc)
ax3.set(title='obtuse=True, reverse=True')
ax3.text(**angle_text)
arc, angle_text = get_arc_patch(lines, radius=(2,1))
ax4.add_artist(arc)
ax4.set(title='radius=(2,1)')
ax4.text(**angle_text)
plt.tight_layout()
plt.show()
I was looking for more of an all in one solution and found the AngleAnnotation class. I highly recommend it.
It is often useful to mark angles between lines or inside shapes with a circular arc. While Matplotlib provides an Arc, an inherent problem when directly using it for such purposes is that an arc being circular in data space is not necessarily circular in display space. Also, the arc's radius is often best defined in a coordinate system which is independent of the actual data coordinates - at least if you want to be able to freely zoom into your plot without the annotation growing to infinity.
You can find it here https://matplotlib.org/stable/gallery/text_labels_and_annotations/angle_annotation.html
I save it as AngleAnnotation.py (of course you can name it differently) in my working directory and import it in my code with
from AngleAnnotation import AngleAnnotation
here is a snippet of how I use it:
...
#intersection of the two lines
center = (0.0,0.0)
#any point (other than center) on one line
p1 = (6,2)
# any point (other than center) on the other line
p2 = (6,0)
# you may need to switch around p1 and p2 if the arc is drawn enclosing the lines instead
# of between
# ax0 is the axes in which your lines exist
# size sets how large the arc will be
# text sets the label for your angle while textposition lets you rougly set where the label is, here "inside"
# you can pass kwargs to the textlabel using text_kw=dict(...)
# especially useful is the xytext argument which lets you customize the relative position of your label more precisely
am1 = AngleAnnotation(center, p1, p2, ax=ax0, size=130, text="some_label", textposition = "inside", text_kw=dict(fontsize=20, xytext = (10,-5)))
You can find many more details in the link above. It's working for me on matplotlib 3.4.2 right now.
I find TomNorway's approach better, it has more flexibility in other cases than the accepted answer. I tested the code and made some quick fixes for even more applicability by creating a class.
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Arc
class LinesAngles:
def __init__(self, line1, line2, radius=None, flip=False, obtuse=False, reverse=False, dec=0, fontsize=8, title=""):
"""
line1: list of two points, of shape [[x0, y0], [x1, y1]]
line2: list of two points, of shape [[x0, y0], [x1, y1]]
radius: None, float or tuple of floats. If None, is set to half the length
of the shortest line orgio: If True, draws the arc around the point (0,0). If False, estimates
the intersection of the lines and uses that point.
flip: If True, flips the arc to the opposite side by 180 degrees
obtuse: If True, uses the other set of angles. Often used with reverse=True.
reverse: If True, reverses the two angles so that the arc is drawn "the opposite way around the circle"
dec: The number of decimals to round to
fontsize: fontsize of the angle label
title: Title of the plot
"""
self.line1 = line1
self.line2 = line2
self.lines = [line1, line2]
self.radius = radius
self.flip = flip
self.obtuse = obtuse
self.reverse = reverse
self.dec = dec
self.fontsize = fontsize
self.title = title
def halfangle(self,a, b) -> float:
"""
Gets the middle angle between a and b, when increasing from a to b
a: float, angle in degrees
b: float, angle in degrees
returns: float, angle in degrees
"""
if b < a:
b += 360
return (a + b)/2 % 360
def get_arc_patch(self, lines: list):
"""
For two sets of two points, create a matplotlib Arc patch drawing
an arc between the two lines.
lines: list of lines, of shape [[(x0, y0), (x1, y1)], [(x0, y0), (x1, y1)]]
returns: Arc patch, and text for the angle label
"""
linedata = [np.array(line.T) for line in lines]
scales = [np.diff(line).T[0] for line in linedata]
scales = [s[1] / s[0] for s in scales]
# Get angle to horizontal
angles = np.array([np.rad2deg(np.arctan(s/1)) for s in scales])
if self.obtuse:
angles[1] = angles[1] + 180
if self.flip:
angles += 180
if self.reverse:
angles = angles[::-1]
angle = abs(angles[1]-angles[0])
if self.radius is None:
lengths = np.linalg.norm(lines, axis=(0,1))
self.radius = min(lengths)/2
# Solve the point of intersection between the lines:
t, s = np.linalg.solve(np.array([line1[1]-line1[0], line2[0]-line2[1]]).T, line2[0]-line1[0])
intersection = np.array((1-t)*line1[0] + t*line1[1])
# Check if radius is a single value or a tuple
try:
r1, r2 = self.radius
except:
r1 = r2 = self.radius
arc = Arc(intersection, 2*r1, 2*r2, theta1=angles[1], theta2=angles[0])
half = self.halfangle(*angles[::-1])
sin = np.sin(np.deg2rad(half))
cos = np.cos(np.deg2rad(half))
r = r1*r2/(r1**2*sin**2+r2**2*cos**2)**0.5
xy = np.array((r*cos, r*sin))
xy = intersection + xy/2
textangle = half if half > 270 or half < 90 else 180 + half
textkwargs = {
'x':xy[0],
'y':xy[1],
's':str(round(angle, self.dec)) + "°",
'ha':'center',
'va':'center',
'fontsize':self.fontsize,
'rotation':textangle
}
return arc, textkwargs
def plot(self) -> None:
"""!
Plot the lines and the arc
"""
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
for line in self.lines:
x,y = line.T
ax.plot(x,y)
ax.axis('equal')
arc, angle_text = self.get_arc_patch(self.lines)
ax.add_artist(arc)
ax.set(title=self.title)
ax.text(**angle_text)
plt.show()
For using it you just create the instance and the plot function.
# lines are formatted like this: [(x0, y0), (x1, y1)]
line1 = np.array([(1,-2), (3,2)])
line2 = np.array([(2,2), (2,-2)])
default = LinesAngles(line1, line2, title="Default")
#Plot single pair of lines
default.plot()
If you still want to plot multiple cases, I created a function that accepts the instances and plots automatically to the subplots you need.
# lines are formatted like this: [(x0, y0), (x1, y1)]
line1 = np.array([(1,-2), (3,2)])
line2 = np.array([(2,2), (2,-2)])
default = LinesAngles(line1, line2, title="Default")
flip = LinesAngles(line1, line2, title='flip=True', flip=True)
obtuse = LinesAngles(line1, line2, title='obtuse=True, reverse=True', obtuse=True, reverse=True)
radius = LinesAngles(line1, line2, title='radius=(2,1)', radius=(2,1))
#Plot single pair of lines
default.plot()
#Plot multiple line pairs
multiple_plot(default, flip, obtuse, radius, num_subplots=4)
Thanks to TomNorway for his answer, all credit to him I only made some modifications.
Related
I need to find the other two points of a rectangle given two points shown in black in the attached drawing. The missing points are showed in yellow width is in red which I do have as well. The rectangle can be arbitrarily rotated.
I also know if the points are on the same side or on opposite sides of the rectangle.
There are four possible arrangements each of which I need to solve for as shown.
In the rectangle, where the rectangle perfectly cuts into two equal triangle.
By applying Pythagoras theorem {hypotenuse^2=base^2+perpendicular^2}.
`base = width of rectangle
perpendicular = length of rectangle
hypotenuse = unknown/desired`
For length of rectangle:
Length of a rectangle = Area ÷ breadth.
If this is not requested please tell.
As you have added the python tag to your question, I assume you want to solve this problem using python.
The Two Scenarios
either the points given represent a diagonal (1)
or the points given represent an edge (2)
(1) Diagonal Approach:
Diagonal Approach Sketch
(Right here, we use the the theorem of Thales. If you don't know it, just look it up. It's quite useful.)
(2) Edge Approach:
Edge Approach Sketch
Python Code
This is pure calculation. Just change the properties at the very end of this script.
import math
import numpy as np
# lovely method by mujjiga
# from https://stackoverflow.com/questions/55816902/finding-the-intersection-of-two-circles
# returns intersections of two circles
def get_intersections(x0, y0, r0, x1, y1, r1):
# circle 1: (x0, y0), radius r0
# circle 2: (x1, y1), radius r1
d = math.sqrt((x1-x0)**2 + (y1-y0)**2)
# non intersecting
if d > r0 + r1:
return None
# One circle within other
if d < abs(r0-r1):
return None
# coincident circles
if d == 0 and r0 == r1:
return None
else:
a = (r0**2-r1**2+d**2)/(2*d)
h = math.sqrt(r0**2-a**2)
x2 = x0+a*(x1-x0)/d
y2 = y0+a*(y1-y0)/d
x3 = x2+h*(y1-y0)/d
y3 = y2-h*(x1-x0)/d
x4 = x2-h*(y1-y0)/d
y4 = y2+h*(x1-x0)/d
return (x3, y3, x4, y4)
# returns None or 4 possible points
def get_unknown_points(p1, p2, width, is_diagonal):
# convert tuples/lists to nummpy arrays
p1 = np.array(p1, dtype=float)
p2 = np.array(p2, dtype=float)
# vector from p1 to p2
p1_to_p2 = p2 - p1
# magnitude/length of this vector
length = np.linalg.norm(p2 - p1)
if is_diagonal:
mid = p1 + 0.5 * p1_to_p2
mid_radius = length * 0.5
points = get_intersections(
p1[0], p1[1], width, mid[0], mid[1], mid_radius)
# no intersections found
if points is None:
return None
other_points = get_intersections(
p2[0], p2[1], width, mid[0], mid[1], mid_radius)
# return the two different possibilities
possibilities = []
possibilities.append(
((points[0], points[1]), (other_points[0], other_points[1])))
possibilities.append(
((points[2], points[3]), (other_points[2], other_points[3])))
return possibilities
# p1 and p2 do not represent the diagonal
else:
# get a perpendicular vector regarding p1_to_p2 (taken from https://stackoverflow.com/questions/33658620/generating-two-orthogonal-vectors-that-are-orthogonal-to-a-particular-direction)
perpendicular_vector = np.random.randn(2)
perpendicular_vector -= perpendicular_vector.dot(
p1_to_p2) * p1_to_p2 / np.linalg.norm(p1_to_p2)**2
# make length of vector correspond to width
perpendicular_vector /= np.linalg.norm(perpendicular_vector)
perpendicular_vector *= width
# add this vector to p1 and p2 and return both possibilities
possibilities = []
possibilities.append(
((p1[0] + perpendicular_vector[0], p1[1] + perpendicular_vector[1]), (p2[0] + perpendicular_vector[0], p2[1] + perpendicular_vector[1])))
possibilities.append(
((p1[0] - perpendicular_vector[0], p1[1] - perpendicular_vector[1]), (p2[0] - perpendicular_vector[0], p2[1] - perpendicular_vector[1])))
return possibilities
# change these properties
p1 = (4, 5)
p2 = (5, 1)
diagonal = True
width = 1
points = get_unknown_points(p1, p2, width, diagonal)
# output
if points is None:
print("There are no points that can be calculated from the points given!")
else:
print(
f"Possibilty 1: \n\tPoint1: {points[0][0]} \n\tPoint2: {points[0][1]}")
print(
f"Possibilty 2: \n\tPoint1: {points[1][0]} \n\tPoint2: {points[1][1]}")
Visualization
If you want to see the results visually, just append these lines of code to the end of the upper script.
import matplotlib.pyplot as plt
# displaying results
if points is not None:
p1 = np.array(p1, dtype=float)
p2 = np.array(p2, dtype=float)
fig, ax = plt.subplots()
ax.set_xlim((-1, 10))
ax.set_ylim((-1, 10))
if diagonal:
dist = np.linalg.norm(p2 - p1)
mid = p1 + 0.5 * (p2 - p1)
mid_radius = dist * 0.5
circle2 = plt.Circle(mid, mid_radius, color='orange', fill=False)
circle3 = plt.Circle(p1, width, color='g', fill=False)
circle1 = plt.Circle(p2, width, color='g', fill=False)
ax.add_artist(circle1)
ax.add_artist(circle2)
ax.add_artist(circle3)
plt.plot(p1, p2, '.', color='black')
print(points[0][1])
plt.plot([points[0][0][0], points[0][1][0]], [
points[0][0][1], points[0][1][1]], '.', color='red')
plt.plot([points[1][0][0], points[1][1][0]], [
points[1][0][1], points[1][1][1]], '.', color='blue')
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
Results
Diagonal Approach Example
Edge Approach Example
A spiral is a flat curve that rotates around a central axis.
I have a drawing of a parkinsonian patient that is based on a spiral.
As you can see, this image of the patient's drawing oscillates around the base spiral. What I would like to do is the following: "unroll" the spiral so that both the oscillation of the drawing and the spiral itself is based on a straight line, that is, to linearize the spiral. How can I do this?
Here is a possible approach in two parts.
The first part tries to align a spiral with the image. The simplest spiral is an Archimedian spiral where the radius and the angle are linearly coupled. By plotting and looking at the coordinates, the limits for an approximate scale for the x and the y directions are found. The result isn't perfect. Maybe the given image isn't nicely scanned, but just a photo giving rise to deformations or the original spiral wasn't a perfect Archimedian spiral. (Also, a png file would be strongly preferred instead of the given jpg). Anyway, the scale is good enough to give an idea how the algorithm would work, preferably starting from an exact scan.
The next part goes through each pixel of the image and finds it corresponding angle and distance to the center (using the scaling found in the first part). The next step is to find how many times the angle has gone around (in multiples of 2 pi), choosing the closest match. Subtracting the radius from the angle would straighten the spiral.
Some code to illustrate the idea.
import numpy as np
from matplotlib import pyplot as plt
import imageio
fig, ax = plt.subplots()
img = imageio.imread('spiral_follow.jpg')
# the image extent is set using trial and error to align with the spiral equation;
# the center of the spiral should end up with coordinates 0,0
x0, x1, y0, y1 = extent = [-17.8, 16, 13, -16.8]
ax.imshow(img, extent=extent)
# t=17.4 is about where the spiral ends; the exact value is not important
t = np.linspace(0, 17.4, 1000)
r = t
theta = t
sx = r * np.sin(theta)
sy = r * np.cos(theta)
ax.plot(sx, sy, c='lime', lw=6, alpha=0.4) # plot the spiral over the image
# r_p and theta_p are the polar coordinates of the white pixels
r_p = []
theta_p = []
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if img[i,j] > 127: # the black pixels are 0, the white are 255; 127 is the middle
# transform from pixel coordinates (i,j) to the coordinatets of the spiral (x,y)
x = x0 + j * (x1 - x0) / (img.shape[1] - 1)
y = y1 + i * (y0 - y1) / (img.shape[0] - 1)
# transform from carthesian (x,y) to polar coordinates (theta,r)
theta = np.arctan2(x, y)
r = np.sqrt(x*x+y*y)
# the following code tries to find out how many times 2pi should be added to theta
# in order to correspond best to r
k = np.round((r - theta) / (2 * np.pi))
nearest_theta = theta + 2 * k * np.pi
theta_p.append(nearest_theta)
r_p.append(nearest_theta - r)
plt.show()
fig, ax = plt.subplots()
ax.set_facecolor('black')
ax.scatter(theta_p, r_p, s=1, lw=0, color='white')
plt.show()
The aligned spiral:
The straightened spiral:
How to create an ellipse from known axis coordinates and peak radius ?
From picture below :
Point A and Point B is know
R is a result of fresnelZone calculation (in Meters).
Point X is a Centroid of LineString AB
I Also read :
this
and
this
But I don't know how to implement it.
one might proceed for example as:
#!/usr/bin/env python
import math
from shapely.geometry import Point
from shapely.affinity import scale, rotate
#input parameters
A = Point(1, 1)
B = Point(4, 5)
R = 1
d = A.distance(B)
#first, rotate B to B' around A so that |AB'| = |AB| and B'.y = A.y
#and then take S as midpoint of AB'
S = Point(A.x + d/2, A.y)
#alpha represents the angle of this rotation
alpha = math.atan2(B.y - A.y, B.x - A.x)
#create a circle with center at S passing through A and B'
C = S.buffer(d/2)
#rescale this circle in y-direction so that the corresponding
#axis is R units long
C = scale(C, 1, R/(d/2))
#rotate the ellipse obtained in previous step around A into the
#original position (positive angles represent counter-clockwise rotation)
C = rotate(C, alpha, origin = A, use_radians = True)
for x,y in C.exterior.coords:
print(x, y)
I'm struggling with a similar problem.
I also want to make a Fresnel Zone, but I want to plot it among the LOS, which is the line that connects the point A and B.
Using the code provided by ewcz I added the line and plotted everything.
The results that the rotated line, does not correspond to the axis of the ellipse, and thus it not corresponds to the LOS.
#!/usr/bin/env python
import math
from shapely.geometry import Point, LineString
from shapely.affinity import scale, rotate
from matplotlib import pyplot as plt
#input parameters
A = Point(0, 0)
B = Point(400, 10)
R = 5
d = A.distance(B)
#first, rotate B to B' around A so that |AB'| = |AB| and B'.y = A.y
#and then take S as midpoint of AB'
S = Point(A.x + d/2, A.y)
#Make a straight line
LOS = LineString([(A.x, A.y), (B.x, A.y)])
#alpha represents the angle of this rotation
alpha = math.atan2(B.y - A.y, B.x - A.x)
#create a circle with center at S passing through A and B'
C = S.buffer(d/2)
#rescale this circle in y-direction so that the corresponding
#axis is R units long
C = scale(C, 1, R/(d/2))
#rotate the ellipse obtained in previous step around A into the
#original position (positive angles represent counter-clockwise rotation)
C = rotate(C, alpha, origin=A, use_radians=True)
f_x, f_y = C.exterior.xy
#plot the ellipse
plt.plot(f_x, f_y)
#rotate the line in the same way as the ellipse
LOS_R = rotate(LOS, alpha, origin=A, use_radians=True)
f_x, f_y = LOS_R.xy
#plot the line
plt.plot(f_x, f_y)
plt.show()
The resulting plot is:
Plotted image with matplot
I've been trying to push the boundaries of matplotlib's patches and instruct it to draw a rounded FancyArrowPatch with a directional arrow on its midpoint. This would prove incredibly useful in a network representation I am trying to create.
My coding hours with python are not yet in the double digit, so I can't say I have a clear understanding of matplotlib's patches.py, but I have narrowed down the solution to two possible strategies:
the smart, possibly pythonic way: create a custom arrowstyle class which further requires a modification of the _get_arrow_wedge() function to include a midpoint coordinates. This may be beyond my possibilities for now, or
the lazy way: extract the midpoint coordinates from an elicited FancyArrowPatch and draw the desired arrowstyle on such coordinates.
Of course, so far I've chosen the lazy way. I did some early experimenting with extracting the midpoint coordinates of a curved FancyArrowPatch using get_path() and get_path_in_displaycoord(), but I can't seem to predict the precise midpoint coordinates. Some help would be very appreciated.
My fiddling so far:
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch
n1 = (2,3)
n2 = (4,6)
# Try with multiple arc radius sizes, draw a separate plot each time
for rad in range(20):
#setup figure
figure = plt.figure()
ax = plt.subplot(111)
plt.annotate('rad:' + str(rad/25.),xy=(2,5))
# create rounded fancyarrowpatch
t = FancyArrowPatch(posA=n1,posB=n2,
connectionstyle='arc3,rad=%s'%float(rad/25.),
arrowstyle='->',
shrinkA=0,
shrinkB=0,
mutation_scale=0.5)
# extract vertices from get_path: points P#
path = t.get_path().vertices.tolist()
lab, px, py = ['P{0}'.format(i) for i in range(len(path))], [u[0] for u in path],[u[1] for u in path]
for i in range(len(path)):
plt.annotate(lab[i],xy=(px[i],py[i]))
# extract vertices from get_path_in_displaycoord (but they are useless) : points G#
newpath = t.get_path_in_displaycoord()
a,b = newpath[0][0].vertices.tolist(), newpath[0][1].vertices.tolist()
a.extend(b)
glab, gx, gy = ['G{0}'.format(i) for i in range(len(a))], [u[0] for u in a],[u[1] for u in a]
for i in range(len(a)):
plt.annotate(glab[i],xy=(gx[i],gy[i]))
#point A: start
x1, y1 = n1
plt.annotate('A',xy=(x1,y1))
#point B:end
x2, y2 = n2
plt.annotate('B',xy=(x2,y2))
#point M: the 'midpoint' as defined by class Arc3, specifically its connect() function
x12, y12 = (x1 + x2) / 2., (y1 + y2) / 2.
dx, dy = x2 - x1, y2 - y1
cx, cy = x12 + (rad/100.) * dy, y12 - (rad/100.) * dx
plt.annotate('M',xy=(cx,cy))
#point O : midpoint between M and P1, the second vertex from get_path
mx,my = (cx + px[1])/2., (cy + py[1])/2.
plt.annotate('O',xy=(mx,my))
ax.add_patch(t)
plt.scatter([x1,cx,x2,mx,gx].extend(px),[y1,cy,y2,my,gy].extend(py))
plt.show()
EDIT: taking onboard #cphlewis suggestions: I tried to reconstruct the Bezier curve:
def bezcurv(start,control,end,tau):
ans = []
for t in tau:
B = [(1-t)**2 * start[i] + 2*(1-t)*t*end[i] + (t**2)*control[i] for i in range(len(start))]
ans.append(tuple(B))
return ans
I thus add the generated line to the original plot:
tau = [time/100. for time in range(101)]
bezsim = bezcurv(n1,n2,(cx,cy),tau)
simx,simy = [b[0] for b in bezsim], [b[1] for b in bezsim]
The green line below is (should be?) the reconstructed bezier curve, though it's clearly not.
After much struggling, I convinced myself that to solve this I had to part away from the FancyArrowPatch suite and create something from scratch. Here is a working solution that, far from fulfilling any perfectionist spirit, satisfied me:
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import seed, randint
# Build function that connects two points with a curved line,
# and an arrow on the middle of it
seed(1679)
narrow = 3
rad_one = 50
numpoints = 3
random_points = list(randint(1,20,[numpoints,4]))
rpoints = [[(a,b),(c,d)] for a,b,c,d in random_points]
def curvline(start,end,rad,t=100,arrows=1,push=0.8):
#Compute midpoint
rad = rad/100.
x1, y1 = start
x2, y2 = end
y12 = (y1 + y2) / 2
dy = (y2 - y1)
cy = y12 + (rad) * dy
#Prepare line
tau = np.linspace(0,1,t)
xsupport = np.linspace(x1,x2,t)
ysupport = [(1-i)**2 * y1 + 2*(1-i)*i*cy + (i**2)*y2 for i in tau]
#Create arrow data
arset = list(np.linspace(0,1,arrows+2))
c = zip([xsupport[int(t*a*push)] for a in arset[1:-1]],
[ysupport[int(t*a*push)] for a in arset[1:-1]])
dt = zip([xsupport[int(t*a*push)+1]-xsupport[int(t*a*push)] for a in arset[1:-1]],
[ysupport[int(t*a*push)+1]-ysupport[int(t*a*push)] for a in arset[1:-1]])
arrowpath = zip(c,dt)
return xsupport, ysupport, arrowpath
def plotcurv(start,end,rad,t=100,arrows=1,arwidth=.25):
x, y, c = curvline(start,end,rad,t,arrows)
plt.plot(x,y,'k-')
for d,dt in c:
plt.arrow(d[0],d[1],dt[0],dt[1], shape='full', lw=0,
length_includes_head=False, head_width=arwidth)
return c
#Create figure
figure = plt.figure()
ax = plt.subplot(111)
for n1,n2 in rpoints:
#First line
plotcurv(n1,n2,rad_one,200,narrow,0.5)
#Second line
plotcurv(n2,n1,rad_one,200,narrow,0.5)
ax.set_xlim(0,20)
ax.set_ylim(0,20)
plt.show
I have tested it with three random couple of points, plotting back and forth lines. Which gives the figure below:
The function allows for the user to set a number of desired arrow-heads, and it places them evenly on the plotted Bezier, making sure the appropriate direction is represented. However, because the Bezier curve is not exactly an 'arc', I heuristically push the start of the arrow-heads to make them look more centered. Any improvement to this solution will be greatly appreciated.
I mean the cone or disk is moving or rotating with its axis of symmetry. To be exact, I am creating this axis, which is constantly changing with time:
line = ax.plot([x,0],[y,0],[z,z- n_o],color='#000066', marker= 'o')
I need the face of the cone or circle always perpendicular to that axis. I tried simpler one first by creating a 2D circle then lift it up to the position I want:
circle = Circle((0, 0), .3, color='r')
ax.add_patch(circle)
art3d.pathpatch_2d_to_3d(circle, z=1)
but that won't make the face of the circle perpendicular to the moving axis. I wonder is there any function in matplotlib I can use to rotate that face of the cone/circle?
If, I started from another way by creating a 3D object, like an ellipsoid, the problem remains: how do I let the object moving with its axis of symmetry like a rigid body(stick with its axis) rather than a lantern hanging there(attached to a fixed point only)?
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x=np.cos(u)*np.sin(v)
y=np.sin(u)*np.sin(v)
z=.3*np.cos(v)
ax.plot_wireframe(x, y, z, color="r")
from mpl_toolkits.mplot3d import Axes3D
def euler_rot(XYZ,phi,theta,psi):
'''Returns the points XYZ rotated by the given euler angles'''
ERot = np.array([[np.cos(theta)*np.cos(psi),
-np.cos(phi)*np.sin(psi) + np.sin(phi)*np.sin(theta)*np.cos(psi),
np.sin(phi)*np.sin(psi) + np.cos(phi)*np.sin(theta)*np.cos(psi)],
[np.cos(theta)*np.sin(psi),
np.cos(phi)*np.cos(psi) + np.sin(phi)*np.sin(theta)*np.sin(psi),
-np.sin(phi)*np.cos(psi) + np.cos(phi)*np.sin(theta)*np.sin(psi)],
[-np.sin(theta),
np.sin(phi)*np.cos(theta),
np.cos(phi)*np.cos(theta)]])
return ERot.dot(XYZ)
u = np.linspace(0,2*np.pi,50)
num_levels = 10
r0 = 1 # maximum radius of cone
h0 = 5 # height of cone
phi = .5 # aka alpha
theta = .25 # aka beta
psi = 0 # aka gamma
norm = np.array([0,0,h0]).reshape(3,1)
normp = euler_rot(norm,phi,theta,psi)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot([0,normp[0]],[0,normp[1]],zs= [0,normp[2]])
x = np.hstack([r0*(1-h)*np.cos(u) for h in linspace(0,1,num_levels)])
y = np.hstack([r0*(1-h)*np.sin(u) for h in linspace(0,1,num_levels)])
z = np.hstack([np.ones(len(u))*h*h0 for h in linspace(0,1,num_levels)])
XYZ = np.vstack([x,y,z])
xp,yp,zp = euler_rot(XYZ,phi,theta,psi)
ax.plot_wireframe(xp,yp,zp)
This will draw a cone around the line pointing along the direction of the z-axis after rotation through the Euler angles phi,theta,psi. (in this case psi will have no effect as the cone is axi-symmetric around the z-axis) Also see rotation matrix.
To draw a single circle shifted along the normal by h0:
x=r0*np.cos(u)
y=r0*np.sin(u)
z=h0*np.ones(len(x))
XYZ = np.vstack([x,y,z])
xp,yp,zp = euler_rot(XYZ,phi,theta,psi)
ax.plot(xp,yp,zs=zp)
It is left as an exercise to get the euler angles from a given vector.
euler_rot in a gist