【问题标题】:Changing subplot size for displaying ellipse correctly更改子图大小以正确显示椭圆
【发布时间】:2020-02-05 19:36:27
【问题描述】:

我正在尝试为均匀分布的点绘制置信椭圆。使用 Matplotlib 绘制椭圆和散点图时,我发现椭圆的一部分被子图剪裁了。鉴于herehereherehere,我尝试实施此处建议的其他解决方案。但无法更正显示的情节。

如何更改此子图的大小以正确完整地显示椭圆?

椭圆生成代码:multidimensional confidence intervals

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

def eigsorted(cov):
    vals, vecs = np.linalg.eigh(cov)
    order = vals.argsort()[::-1]
    return vals[order], vecs[:,order]

nstd = 2

fig = plt.figure(1, figsize=(12, 5))
#ax = plt.subplots(111)
ax = fig.add_subplot(111, aspect='equal')
test1 = np.random.uniform(40, 60, 1000)
test2 = np.random.uniform(100, 120, 1000)
cov = np.cov(test1, test2)
vals, vecs = eigsorted(cov)
theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
w, h = 2 * nstd * np.sqrt(vals)
ell = Ellipse(xy=(np.mean(test1), np.mean(test2)),
              width=w, height=h,
              angle=theta, color='black')
ell.set_facecolor('none')
ax.add_artist(ell)
plt.scatter(test1, test2)
plt.show()

【问题讨论】:

  • 椭圆是一个补丁。使用ax.add_patch(ell)添加。
  • 完美!谢谢!
  • @ImportanceOfBeingErnest - 关于类似问题的任何想法,即在图中添加补丁无法正确拟合椭圆:stackoverflow.com/questions/58289316/…

标签: python matplotlib ellipse


【解决方案1】:

正如@ImportanceOfBeingEarnest 正确评论的那样,需要添加一个补丁才能正确显示椭圆。更新下面的代码以供其他人将来参考。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

def eigsorted(cov):
    vals, vecs = np.linalg.eigh(cov)
    order = vals.argsort()[::-1]
    return vals[order], vecs[:,order]

nstd = 2

fig = plt.figure(1, figsize=(12, 5))
#ax = plt.subplots(111)
ax = fig.add_subplot(111, aspect='equal')
test1 = np.random.uniform(40, 60, 1000)
test2 = np.random.uniform(100, 120, 1000)
cov = np.cov(test1, test2)
vals, vecs = eigsorted(cov)
theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
w, h = 2 * nstd * np.sqrt(vals)
ell = Ellipse(xy=(np.mean(test1), np.mean(test2)),
              width=w, height=h,
              angle=theta, color='black')
ell.set_facecolor('none')

#Corrected code for displaying ellipse correctly
ax.add_patch(ell)

plt.scatter(test1, test2)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-21
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2011-02-15
    • 2023-01-29
    相关资源
    最近更新 更多