I have been exploring many options to do this. The idea is that I will plot points and a curve will be drawn through them in order, however, the curve will not connect the starting and ending points.
This is what I have so far:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import CubicSpline
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = []
y = []
pts: list[tuple[float, float]] = []
xnew = np.linspace(start=0, stop=10, num=1000)
fig = plt.figure()
graph = plt.subplot(xlim=(0, 10), ylim=(0, 10))
pt_sorter = lambda li: li[0]
def mouse_event(event):
global xnew
pts.append((event.xdata, event.ydata))
pts.sort(key=pt_sorter)
x = [pt[0] for pt in pts]
y = [pt[1] for pt in pts]
graph.cla()
graph.set_xlim([0, 10])
graph.set_ylim([0, 10])
xnew = np.linspace(start=min(x), stop=max(x), num=1000)
graph.plot(x, y, ls='', marker='o', color='r')
if len(pts) > 2:
spl = CubicSpline(np.array(x), np.array(y))
graph.plot(xnew, spl(xnew), color='b')
plt.show()
cid = fig.canvas.mpl_connect('button_press_event', mouse_event)
plt.show()
This approach using a CubicSpline and scipy interpolate allows me to interactively plot points and draw a smooth curve through them. However, it does not support "doubling back" on the x-axis. What I mean is I can't have the curve go right and then cut back left. I can't figure out how to do this. I'm trying to make a route planning software. Maybe drawing the curve in matplotlib wasn't the greatest idea. I'm not sure how else to do it though. Any pointers would be appreciated.