matplotlib中具有不同角度和偏心的椭圆

2024-10-01 11:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用省略号作记号。下面是一个示例代码,它使一个大椭圆现在实际上是一个圆。在

#! /usr/bin/env python3.2
import numpy as np
import pylab
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.patches import Ellipse

PlotFileName="test.pdf"
pdf = PdfPages(PlotFileName)
fig=plt.figure(1)
ax1=fig.add_subplot(111)
x_lim=3
plt.xlim([0,x_lim])
plt.ylim([0,x_lim])

F=pylab.gcf()
DefSize = F.get_size_inches()

#These lines have a true angle of 45 degrees, only as a reference:
offset_along_x=x_lim-(x_lim/ax_ratio)
ax1.plot([offset_along_x/2, x_lim-(offset_along_x/2)], [0, x_lim], "b")
ax1.plot([offset_along_x/2, x_lim-(offset_along_x/2)], [x_lim, 0], "b")

e=0.0
theta=0
maj_ax=2
min_ax=maj_ax*np.sqrt(1-e**2)
xconst=(DefSize[1]/DefSize[0])*np.cos(theta*np.pi/180)-np.sin(theta*np.pi/180)
yconst=np.cos(theta*np.pi/180)+(DefSize[1]/DefSize[0])*np.sin(theta*np.pi/180)
print("xconstant= {}".format(xconst))
print("yconstant= {}".format(yconst))
ax1.add_artist(Ellipse((x_lim/2, x_lim/2), xconst*maj_ax, yconst*min_ax, angle=theta, facecolor="green", edgecolor="black",zorder=2, alpha=0.5))

pdf.savefig(fig)
pdf.close()
plt.close()

虽然在这个简化的例子中,ax1.axis("equal")将给出一个纯圆,但是在我最后的绘图中,这个命令将破坏整个绘图(比例不相等)。所以我想在不使用ax1.axis("equal")的情况下制作一个通用椭圆工具。如你所见,你可以在这个程序中设置偏心率和长轴的倾角。在

问题: 问题似乎是我不明白matplotlib如何旋转它的图像。如果将theta的值改为0或90以外的值,则对象将不再是圆。使用ax1.axis("equal")时,无论theta的值是多少,输出都是一个圆。所以我的第一个问题是:在改变theta时,我应该做些什么来保持输出为一个圆。我假设一旦我解决了这个问题,它也适用于椭圆。有人能帮我吗?我真的很感激。在


Tags: importpdfmatplotlibasnppipltax
1条回答
网友
1楼 · 发布于 2024-10-01 11:24:12

在matplotlib中,eclipse的位置和形式是通过先缩放到高度和宽度,然后围绕中心旋转,然后转换到所需位置来设置的。所以旋转和缩放高度和before may mork(就像在你的脚本中一样),但是很难做到完全正确(你可能需要缩放和反转旋转,但是我的变换数学是生疏的)。在

如果要正确缩放椭圆的形状,则需要将椭圆类子类化并重新定义_recompute_transform函数:

from matplotlib import transforms

class TransformedEllipse(Ellipse):

    def __init__(self, xy, width, height, angle=0.0, fix_x = 1.0, **kwargs):
        Ellipse.__init__(self, xy, width, height, angle, **kwargs)

        self.fix_x = fix_x

    def _recompute_transform(self):

        center = (self.convert_xunits(self.center[0]),
                  self.convert_yunits(self.center[1]))
        width = self.convert_xunits(self.width)
        height = self.convert_yunits(self.height)
        self._patch_transform = transforms.Affine2D() \
            .scale(width * 0.5, height * 0.5) \
            .rotate_deg(self.angle) \
            .scale(self.fix_x, 1) \
            .translate(*center)

然后像这样使用它:

^{pr2}$

另外,我假设ax_ratioy_lim / x_lim!在

相关问题 更多 >