Issue
I have been trying to create a slight curve between two points using Python and Matplotlib. I found a method on here that does apply a curve to the line between two points but not in the way I expected/was hoping for. Below is the code I am currently using to draw the curved line.
Current graph: Currently what line looks like
Desired graph: Desired curved line
Currently it is almost a 90 deg. angle but I am trying to achieve a more even curve. This solution does seem to achieve the desired results for smaller values, but when using larger values for the x/y coords this is what I am seeing.
p1 = [125, -203]
p2 = [49, -75]
plt.plot(p1[0], p1[1], marker="o", markersize=10, color="black", label="P1")
plt.plot(p2[0], p2[1], marker="o", markersize=10, color="red", label="P1")
plt.plot((p1[0], p2[0]),
(p1[1], p2[1]),
linewidth=5,
label="Straight line")
x, y = draw_curve(p1, p2)
plt.plot(x, y, linewidth=5, label="Curved line", color="orange")
plt.show()
def draw_curve(p1, p2):
a = (p2[1] - p1[1]) / (np.cosh(p2[0]) - np.cosh(p1[0]))
b = p1[1] - a * np.cosh(p1[0])
x = np.linspace(p1[0], p2[0], 100)
y = a * np.cosh(x) + b
return x, y
Solution
There are infinitely many ways to come up with a curve. One way to come up with a curve that you can manually tune (the "angle") is to add a third point where you would like the curve to pass through:
p1 = [125, -203]
p2 = [49, -75]
p3 = [90, -100] # the third point
plt.plot(p1[0], p1[1], marker="o", markersize=10, color="black", label="P1")
plt.plot(p2[0], p2[1], marker="o", markersize=10, color="red", label="P1")
plt.plot((p1[0], p2[0]),
(p1[1], p2[1]),
linewidth=5,
label="Straight line")
def draw_curve(p1, p2, p3):
f = np.poly1d(np.polyfit((p1[0], p2[0], p3[0]), (p1[1], p2[1], p3[1]), 2))
x = np.linspace(p1[0], p2[0], 100)
return x, f(x)
x, y = draw_curve(p1, p2, p3)
plt.plot(x, y, linewidth=5, label="Curved line", color="orange")
plt.show()
Answered By - Z Li
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.