我的目标是计算两个椭圆相交的面积。下面计算两个固定坐标之间的面积,但我希望使用一个椭圆的移动坐标来迭代这个过程,同时保持第二个椭圆的固定。
在下面使用时,int_err = int_err_prime
将保持不变,而 ellipse1
将使用 ellipse2
中来自 X
和 Y
的坐标。
预期的输出将有望返回每个时间点的面积,四舍五入到小数点后两位,作为标记为 df
的单独列。
'Area'
预期输出:
df = pd.DataFrame({
'Time' : [1,2,3,4,5],
'X' : [3.0,4.5,5.0,10.0,3.0],
'Y' : [1.0,0.0,-1.0,-2.0,-3.0],
})
from matplotlib import pyplot as plt
from shapely.geometry.point import Point
from shapely import affinity
from matplotlib.patches import Polygon
import numpy as np
def create_ellipse(center, lengths, angle = 0):
"""
create a shapely ellipse. adapted from
https://gis.stackexchange.com/a/243462
"""
circ = Point(center).buffer(1)
ell = affinity.scale(circ, int(lengths[0]), int(lengths[1]))
ellr = affinity.rotate(ell, angle)
return ellr
fig,ax = plt.subplots(figsize = (6,6))
ax.set_xlim([-20,20])
ax.set_ylim([-20,20])
ellipse1 = create_ellipse((0,0),(5,10),0)
verts1 = np.array(ellipse1.exterior.coords.xy)
patch1 = Polygon(verts1.T,color = 'red', alpha = 0.5)
ax.add_patch(patch1)
ellipse2 = create_ellipse((3.0,1.0),(5,5),0)
verts2 = np.array(ellipse2.exterior.coords.xy)
patch2 = Polygon(verts2.T,color = 'blue', alpha = 0.5)
ax.add_patch(patch2)
##compute intersect
intersect = ellipse1.intersection(ellipse2)
verts3 = np.array(intersect.exterior.coords.xy)
patch3 = Polygon(verts3.T, facecolor = 'none', edgecolor = 'black')
ax.add_patch(patch3)
##compute intersected area
print(intersect.area)
答案 0 :(得分:2)
如果我明白你的意思,你就快到了;您所需要的只是在数据框中使用一种循环。即使这可能因为应用而效率不高,这也可以解决问题(更好的方法可能是跳到 geopandas,但我认为这里的这种方法对你来说更容易理解):
ellipse1 = create_ellipse((0,0),(5,10),0)
df['ellipse2'] = df[['X', 'Y']].apply(
lambda xy:create_ellipse([*xy],(5,5),0),
axis=1
)
df['Area'] = df['ellipse2'].apply(lambda x: ellipse1.intersection(x).area)
df.drop('ellipse2', axis=1, inplace=True)
print(df)
退货
Time X Y Area
0 1 3.0 1.0 56.518719
1 2 4.5 0.0 41.997447
2 3 5.0 -1.0 36.746078
3 4 10.0 -2.0 0.000000
4 5 3.0 -3.0 54.029912