python - matplotlib中椭圆的坐标
问题描述
我可以使用 matplotlib.patches.Ellipse 绘制一个漂亮的椭圆(平滑且正确)
我想获得平滑椭圆的坐标(一组 x 和 y 坐标)。当我访问椭圆的顶点时,我得到一个非常粗糙的形状,就像代码下方图像中的单位圆一样。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import matplotlib.transforms as transforms
def confidence_ellipse(cov,center, ax, n_std=1.0, facecolor='none', **kwargs):
"""
Create a plot of the covariance confidence ellipse of `x` and `y`
adapted from:
https://matplotlib.org/3.1.0/gallery/statistics/confidence_ellipse.html
Parameters
----------
x, y : array_like, shape (n, )
Input data.
ax : matplotlib.axes.Axes
The axes object to draw the ellipse into.
n_std : float
The number of standard deviations to determine the ellipse's radiuses.
Returns
-------
matplotlib.patches.Ellipse
Other parameters
----------------
kwargs : `~matplotlib.patches.Patch` properties
"""
#cov = np.cov(x, y)
pearson = cov[0, 1]/np.sqrt(cov[0, 0] * cov[1, 1])
# Using a special case to obtain the eigenvalues of this
# two-dimensionl dataset.
ell_radius_x = np.sqrt(1 + pearson)
ell_radius_y = np.sqrt(1 - pearson)
ellipse = Ellipse((0, 0),
width=ell_radius_x * 2,
height=ell_radius_y * 2,
facecolor=facecolor,
**kwargs)
# Calculating the stdandard deviation of x from
# the squareroot of the variance and multiplying
# with the given number of standard deviations.
scale_x = np.sqrt(cov[0, 0]) * n_std
mean_x = center[0]#np.mean(x)
# calculating the stdandard deviation of y ...
scale_y = np.sqrt(cov[1, 1]) * n_std
mean_y = center[1]
transf = transforms.Affine2D() \
.rotate_deg(45) \
.scale(scale_x, scale_y) \
.translate(mean_x, mean_y)
ellipse.set_transform(transf + ax.transData)
# Get the path
path = ellipse.get_path()
# Get the list of path vertices
vertices = path.vertices.copy()
# Transform the vertices so that they have the correct coordinates
xx,yy=vertices.T
return ellipse,xx,yy#ax.add_patch(ellipse)
ax=plt.subplot(111)
cov1 = np.array([[0.2779001, -0.1037428],[-0.1037428 , 0.1353510]])
center1 = np.array([-0.02561743,0.20181786])
ellipse1,xl1,yl1 =confidence_ellipse(cov1,center1, ax, edgecolor='red')
plt.plot(xl1,yl1,color='red')
ax.add_patch(ellipse1)
plt.savefig('ellipse_test_help.pdf')
plt.close()
平滑椭圆和我使用顶点得到的形状
解决方案
推荐阅读
- sorting - 如何获取将在 Rust 中对向量进行排序的索引?
- java - 使用哪种 MIME 类型从 Android Studio 在 Google Drive v3 中上传/下载具有不同扩展名的文件
- java - 面临有关 java 应用程序中内存泄漏的问题。我想在代码的第 2 行关闭 ServerSocketChannel.open()
- huggingface-transformers - 为什么三个嵌入结果与 Transformer 模型如此不同?
- if-statement - 千、百万、十亿和万亿的自定义数字格式
- android - 如果华为设备同时支持 GMS 和 HMS 核心,那为什么 HMS 核心不工作?
- ansible - 适用于生产环境的 Ansible 修补订单/库存逻辑
- plc - 在 TwinCAT 3 PLC 上读取循环时间
- telegram - 如何使用 Telethon 在 Telegram 中编辑消息?
- discord.py - Discord.py 授权让机器人将某人添加到服务器?