Changing plot size in Matplotlib to fit ellipses

半世苍凉 提交于 2019-12-13 03:38:59

问题


I'm plotting confidence ellipses for uniformly distributed points. When plotting the ellipse and the scatter plot using Matplotlib, I find that a portion of the ellipses are clipped by the subplot. So far, I have tried changing the figure sizes, but it does not change the plot.

How do I change the plot size to correctly fit the ellipses within the displayed plot?

Code to generate ellipses: Modified from below link
multidimensional confidence intervals

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from scipy.stats import norm, chi2
sns.set()

def cov_ellipse(cov, q=None, nsig=None, ax=None, **kwargs):

    if q is not None:
        q = np.asarray(q)
    elif nsig is not None:
        q = 2 * norm.cdf(nsig) - 1
    else:
        raise ValueError('One of `q` and `nsig` should be specified.')
    r2 = chi2.ppf(q, 2)

    val, vec = np.linalg.eigh(cov)
    width, height = 2 * np.sqrt(val[:, None] * r2)
    rotation = np.degrees(np.arctan2(*vec[::-1, 0]))

    return ellipse_plot(width, height, rotation, ax, **kwargs)

def ellipse_plot(width, height, rotation, ax=None, **kwargs):

    if ax is None:
        ax = plt.gca()
    ellip = Ellipse(xy=points.mean(axis=0), width=width, height=height, angle=rotation, **kwargs)
    ax.add_patch(ellip)
    return ellip

if __name__ == '__main__':
    #-- Example usage -----------------------
    # Generate some random, correlated data
    mu = [50, 105]
    omega = np.array([1, 0.2, 0.2, 0.5]).reshape((2, 2))

    points = np.random.multivariate_normal(mu, omega, 1000)
    x1 = np.random.uniform(40, 60, 1000)
    y1= np.random.uniform(100, 120, 1000)
    points1 = np.random.uniform(40,60,[1000,2])
    cov = np.cov(points1, rowvar=False)
    plt.figure(figsize=(4, 3))
    plt.plot(x1, y1, 'ro', alpha=0.5)
    # Plot a transparent 3 standard deviation covariance ellipse
    cov_ellipse(cov, q=None, nsig=2, color='green', alpha=0.3)
    cov_ellipse(cov, q=None, nsig=1, color='red', alpha=0.3)
    cov_ellipse(cov, q=None, nsig=3, color='blue', alpha=0.3)
    #sns.jointplot(points[:,0], points[:,1])
    sns.jointplot(x1,y1)
    plt.show()

来源:https://stackoverflow.com/questions/58289316/changing-plot-size-in-matplotlib-to-fit-ellipses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!