3

I want to draw a smooth line through my scatter points. An ellipse won't fit, so I drew a polygon, but I can't get smooth lines with a polygon. I also tried PathPatch, but that way the line doesn't go through the points. Is there any way to force PathPatch to go through the points?

I added an example which hopefully illustrates what I am trying to do. I do not want the hard edges of the black line.

from matplotlib import pyplot as plt
from matplotlib.patches import Ellipse, Polygon

ax = plt.subplot()
ax.set_aspect("equal")
ax.add_artist(Ellipse((0, 0), 10, 5, fill=False, color='green'))

plt.scatter([5, -6, 0, 0], [0, 0, 2.5, -4], marker='X')
ax.add_artist(Polygon([[5, 0], [0, 2.5], [-6, 0], [0, -4]], closed=True, fill=False))

plt.xlim((-6, 6))
plt.ylim((-6, 6))
plt.show()

enter image description here

Zephyr
  • 11,891
  • 53
  • 45
  • 80
HennyKo
  • 712
  • 1
  • 8
  • 19

1 Answers1

2

As explained in this answer, you can use a closed spline to interpolate your data points, for this purpose you can use scipy.interpolate.splprep and scipy.interpolate.splev.
You firstly need to append the first element of both x and y to the end in order to close the spline.

import matplotlib.pyplot as plt
from scipy.interpolate import splprep, splev
import numpy as np


x = [0, 5, 0, -6]
y = [-4, 0, 2, 0]

x.append(x[0])
y.append(y[0])

tck, _ = splprep([x, y], s = 0, per = True)
xx, yy = splev(np.linspace(0, 1, 100), tck, der = 0)


fig, ax = plt.subplots()

ax.scatter(x, y, marker = 'X')
ax.plot(xx, yy, 'green')

plt.show()

enter image description here

Zephyr
  • 11,891
  • 53
  • 45
  • 80