Overlap area of 2 ellipses using matplotlib

2020-03-31 07:24发布

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

I have to ellipses like this:

enter image description here

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

1条回答
一纸荒年 Trace。
2楼-- · 2020-03-31 07:55

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

The resulting plot looks like this:

result of above code

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.

查看更多
登录 后发表回答