UP最近在比赛中,需要绘制地理的气泡图,并且需要绘制椭圆形的,因不想学习arcgis,所以用python绘制,发现现在互联网上缺少相关信息,最近琢磨出来了分享一下。
首先加载扩展库以后,创建一个空地图。
import folium
# 创建空地图
m = folium.Map()
然后创建椭圆的路径,我在这里封装了一个函数,大家照着用就可以。
def ellipse(lot1,lat1,lot2,lat2,R) -> list:
'''
lot1 float:椭圆长轴第一个端点的经度
lat1 float:椭圆长轴第一个端点的纬度
lot2 float:椭圆长轴第二个端点的经度
lat2 float:椭圆长轴第二个端点的纬度
R float:椭圆短轴长短的系数,越大椭圆越接近圆
'''
#input parameters
A = Point(lot1, lat1)
B = Point(lot2, lat2)
d = A.distance(B)
#first, rotate B to B' around A so that |AB'| = |AB| and B'.y = A.y
#and then take S as midpoint of AB'
S = Point(A.x + d/2, A.y)
#alpha represents the angle of this rotation
alpha = math.atan2(B.y - A.y, B.x - A.x)
#create a circle with center at S passing through A and B'
C = S.buffer(d/2)
#rescale this circle in y-direction so that the corresponding
#axis is R units long
C = scale(C, 1, R/(d/2))
#rotate the ellipse obtained in previous step around A into the
#original position (positive angles represent counter-clockwise rotation)
C = rotate(C, alpha, origin = A, use_radians = True)
folium_poly = [[y,x] for x,y in C.exterior.coords]
return folium_poly
然后将创建完成的椭圆形状插入到地理绘图中。
crl = ['red','yellow', 'green'] # 椭圆颜色
folium_poly = [
ellipse(119.218633,34.623384,117.18937,29.266943,1.5),
ellipse(121.379184,32.406006,119.736747,30.23393, 1.3),
ellipse(120.587541, 27.755975,121.959502,30.313353,1)
]
m = folium.Map(location=[31.205472,121.478917],zoom_start=5)
for i in range(3): # 循环添加三个点
folium.Polygon(folium_poly[i],color=crl[i],fill_color=crl[i]).add_to(m)
m # 在notebook 中渲染,如果是想本地保存,运行下面这个
# m.save('XXX.html')
最终效果如图: