[Python] Ellipse.contains_points() in Matplotlib is not working as expected

Discussão em 'Python' iniciado por Stack, Agosto 8, 2025.

  1. Stack

    Stack Membro Participativo

    I am using a slightly modified version of the confidence_ellipse() function given in this example on the Matplotlib documentation. The only difference is I am returning the ellipse variable itself rather than "return ax.add_patch(ellipse)". I generated a random multivariate gaussian dataset for testing using this code:

    data = np.random.multivariate_normal(mean=(1,1), cov=[[0.4, 9],[9, 10]], size=1000)


    And here is the code I used to generate the ellipse and plot the data:

    fig, ax = plt.subplots(figsize = (5,5))

    ellipse = confidence_ellipse(data[:,0], data[:,1], n_std = 2, edgecolor = 'green', facecolor = 'none')

    ax.add_patch(ellipse)
    ax.scatter(data[:,0], data[:,1], s=5, color = 'green', alpha=0.5)

    ax.set_xlabel('x')
    ax.set_ylabel('y')


    This returns something that generally looks like this:

    [​IMG]

    I am trying to figure out which of these points fall within the ellipse. I am using the contains_points() method to do this for the entire dataset:

    ellipse.contains_points(data)


    However, this shows that none of the points are inside the ellipse. So I tried transforming the dataset into the coordinate system of the ellipse:

    t = ellipse.get_transform()
    ellipse.contains_points(t.transform(data))


    This doesn't seem to fix the issue either. It's showing that only 4-5% of the points fall within the ellipse, which is obviously incorrect.

    What am I doing wrong here? Any help is much appreciated!

    Continue reading...

Compartilhe esta Página