pythonmatplotlibellipse

Draw ellipse based on data


I'm trying to draw an ellipse on my plot in such a way to represent a cluster. The code below here plots the first picture. It is within a for loop, but it is not important

native_f1 = [some values here]
native_f2 = [some values here]

ax = plt.subplot(2, 2, index)
ax.scatter(native_f1, native_f2, s=40)
axes = plt.gca()
axes.set_xlim([min(native_f1) - 800, max(native_f1) + 800])
axes.set_ylim([min(native_f2) - 800, max(native_f2) + 800])

no ellipses

Now I'd like to obtain something like that:

enter image description here

How do I draw an ellipse based on the values that I use to plot these graphs ? Thank you


Solution

  • The equation for an ellipse is $\pm b \sqrt{1 - (x-x0)^2/a^2} + y0$, where (x0,y0) is the center of the ellipse. (See Draw ellipses around points for more detail).

    You can find the edges of your ellipse by x2 = max(native_f1), x1 = min(native_f1), y2 = max(native_f2), and y1 = min(native_f2).

    The center (x0,y0) will be ( (x2+x1)/2, (y2+y1)/2 ). The scale of the axis in the y-direction (b) will be (y2-y1)/2 and the scale of the axis in the x-direction (a) will be (x2-x1)/2. Adjust with fudge factors as necessary.

    You can also use matplotlib.patches.Ellipse.