使用matplotlib的2个椭圆的重叠面积 [英] Overlap area of 2 ellipses using matplotlib

查看:398
本文介绍了使用matplotlib的2个椭圆的重叠面积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道是否可以使用matplotlib.patches.Ellipse计算两个椭圆的重叠面积.

Does anyone know if it is possible to calculate the overlapping area of two ellipses using matplotlib.patches.Ellipse.

我必须这样椭圆形:

我想计算重叠面积与各个椭圆的面积之比. 是否可以仅使用matplotlib.patches

And i would like to calculate the ratio between the overlap area and the are of the individual ellipses. Is this possible using only the Ellipse from matplotlib.patches

推荐答案

您无法使用matplotlib计算相交的面积(至少据我所知),但是您可以使用shapely进行计算,然后使用matplotlib可视化结果.这里是一个快速演示:

You cannot compute the area of the intersect with matplotlib (at least not to my knowledge), but you can use shapely to do so and then use matplotlib to visualise the result. Here a quick demo:

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()

##these next few lines are pretty important because
##otherwise your ellipses might only be displayed partly
##or may be distorted
ax.set_xlim([-5,5])
ax.set_ylim([-5,5])
ax.set_aspect('equal')

##first ellipse in blue
ellipse1 = create_ellipse((0,0),(2,4),10)
verts1 = np.array(ellipse1.exterior.coords.xy)
patch1 = Polygon(verts1.T, color = 'blue', alpha = 0.5)
ax.add_patch(patch1)

##second ellipse in red    
ellipse2 = create_ellipse((1,-1),(3,2),50)
verts2 = np.array(ellipse2.exterior.coords.xy)
patch2 = Polygon(verts2.T,color = 'red', alpha = 0.5)
ax.add_patch(patch2)

##the intersect will be outlined in black
intersect = ellipse1.intersection(ellipse2)
verts3 = np.array(intersect.exterior.coords.xy)
patch3 = Polygon(verts3.T, facecolor = 'none', edgecolor = 'black')
ax.add_patch(patch3)

##compute areas and ratios 
print('area of ellipse 1:',ellipse1.area)
print('area of ellipse 2:',ellipse2.area)
print('area of intersect:',intersect.area)
print('intersect/ellipse1:', intersect.area/ellipse1.area)
print('intersect/ellipse2:', intersect.area/ellipse2.area)


plt.show()

结果图如下:

计算出的面积(打印到终端)是:

And the computed areas (printed out to the terminal) are:

area of ellipse 1: 25.09238792436751
area of ellipse 2: 18.81929094327563
area of intersect: 13.656608779925698
intersect/ellipse1: 0.5442530547945023
intersect/ellipse2: 0.7256707397260032

请注意,我修改了代码以根据这篇文章生成椭圆形的多边形.希望这会有所帮助.

Note that I adapted the code to generate the ellipse-shaped polygon from this post. Hope this helps.

这篇关于使用matplotlib的2个椭圆的重叠面积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆