Python Folium地理信息可视化案例

0、背景

在研究、挖掘GPS位置数据、轨迹数据的过程中,地理信息的可视化展示是非常关键的一步。

folium是js上著名的地理信息可视化库leaflet.js为Python提供的接口,通过它,我们可以通过在Python端编写代码操纵数据,来调用leaflet的相关功能,基于内建的osm或自行获取的osm资源和地图原件进行地理信息内容的可视化,以及制作优美的可交互地图。[1]

1、Folium官方文档、官方案例

folium documentation:

https://python-visualization.github.io/folium/

folium examples:

https://nbviewer.jupyter.org/github/python-visualization/folium/tree/master/examples/

 

2、各类基于Folium包的地图类型

2.1 Density Map

def density_map(self, all_data):

    lat = np.array(all_data["lat"][0:len(all_data)])
    lon = np.array(all_data["lon"][0:len(all_data)])

    # duration is not essential
    columns_list = all_data.columns()
    if 'duration' in columns_list:
        duration = np.array(all_data["duration"][0:len(all_data)], dtype=float)
        new_data = [[lat[i], lon[i], duration[i]] for i in range(len(all_data))]
    else:
        new_data = [[lat[i], lon[i]] for i in range(len(all_data))]

    density_map = folium.Map(location=[all_data['lat'].mean(), all_data['lon'].mean()],
                             zoom_start=12,
                             tiles='http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                             attr="http://ditu.amap.com/"
                             )

    HeatMap(new_data, radius=20).add_to(density_map)
    #blur=15, gradient={0.4: 'blue', 0.65: 'lime', 1: 'red'}
    return density_map

folium.map参数:https://python-visualization.github.io/folium/modules.html#module-folium.map

  location:tuple或list类型输入,用于控制初始地图中心点的坐标,格式为(纬度,经度)或[纬度,经度],默认为None

  width:int型或str型,int型时,传入的是地图宽度的像素值;str型时,传入的是地图宽度的百分比,形式为'xx%'。默认为'100%'

  height:控制地图的高度,格式同width

  tiles:str型,用于控制绘图调用的地图样式,默认为'OpenStreetMap',也有一些其他的内建地图样式;也可以传入'None'来绘制一个没有风格的朴素地图,或传入一个URL来使用其它的自选osm

              可选的样式包括:

                 ”OpenStreetMap”

                 ”Stamen Terrain”, “Stamen Toner”, “Stamen Watercolor”

                 ”CartoDB positron”, “CartoDB dark_matter”

                 ”Mapbox Bright”, “Mapbox Control Room” (Limited zoom)

                 ”Cloudmade” (Must pass API key)

                 ”Mapbox” (Must pass API key)

  max_zoom:int型,控制地图可以放大程度的上限,默认为18

  attr:str型,当在tiles中使用自选URL内的osm时使用,用于给自选osm命名

  control_scale:bool型,控制是否在地图上添加比例尺,默认为False即不添加

  no_touch:bool型,控制地图是否禁止接受来自设备的触控事件譬如拖拽等,默认为False,即不禁止

 

Heatmap Parameters

  • data (list of points of the form [latlng] or [latlngweight]) – The points you want to plot. You can also provide a numpy.array of shape (n,2) or (n,3).

  • name (stringdefault None) – The name of the Layer, as it will appear in LayerControls.

  • min_opacity (default 1.) – The minimum opacity the heat will start at.

  • max_zoom (default 18) – Zoom level where the points reach maximum intensity (as intensity scales with zoom), equals maxZoom of the map by default

  • max_val (floatdefault 1.) – Maximum point intensity

  • radius (intdefault 25) – Radius of each “point” of the heatmap

  • blur (intdefault 15) – Amount of blur

  • gradient (dictdefault None) – Color gradient config. e.g. {0.4: ‘blue’, 0.65: ‘lime’, 1: ‘red’}

  • overlay (booldefault True) – Adds the layer as an optional overlay (True) or the base layer (False).

  • control (booldefault True) – Whether the Layer will be included in LayerControls.

  • show (booldefault True) – Whether the layer will be shown on opening (only for overlays).

2.2 Line Map

def line_map(self, all_data):

    line_map = folium.Map(location=[all_data['lat'].mean(), all_data['lon'].mean()],
                          zoom_start=12,
                          tiles='Stamen Terrain',
                          attr="http://ditu.amap.com/")
    route = []
    for name, row in all_data.iterrows():
        route.append([row["lat"], row["lon"]])

    folium.PolyLine(route,
                    weight=5,       # 粗细
                    opacity=0.8,    # 透明度
                    color='orange').add_to(line_map)

    return line_map

folium.PolyLine 参数:

         weight:route粗细

         opacity:透明度

 

 

2.3 Plot Map (结合DBSCAN聚类的聚类结果展示)

def plot_map(self, all_data):
    plot_map = folium.Map(location=[all_data['lat'].mean(), all_data['lon'].mean()],
                          zoom_start=10,
                          tiles='http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                          attr="http://ditu.amap.com/")

    color = ['#F0EDF9', '#E2DBF3', '#D3CAEE', '#B7A6E2', '#A895DD', '#9A83D7', '#8C71D1', '#7D60CC', '#6F4EC6',
             '#613DC1', '#5938B0', '#50329E', '#472D8D', '#3E277B', '#35226A', '#2D1C58', '#241747', '#1B1135',
             '#F0EDF9', '#E2DBF3', '#D3CAEE', '#C5B8E8', '#B7A6E2', '#A895DD', '#9A83D7', '#8C71D1', '#7D60CC',
             '#6F4EC6', '#613DC1', '#5938B0', '#50329E', '#472D8D', '#3E277B', '#35226A', '#2D1C58', '#241747',
             '#1B1135']  # 37种

    for name, row in all_data.iterrows():
        if int(row['classlabel']) == -1:
            folium.Circle(radius=20, location=[row["lat"], row["lon"]], popup="离群--停车点:{0}".format(name),
                          color='black', fill=True, fill_color='black').add_to(plot_map)
        else:
            i = int(row['classlabel'])
            folium.Circle(radius=20, location=[row["lat"], row["lon"]], popup="{0}类--停车点:{1}".format(i, name),
                          color=color[i], fill=True, fill_color=color[i]).add_to(plot_map)

    return plot_map

Python Folium地理信息可视化案例_第1张图片

 

参考资料

[1]https://www.cnblogs.com/feffery/p/9282808.html

[2]色域表供参考https://www.sioe.cn/yingyong/yanse-rgb-16/  by https://blog.csdn.net/junshan2009/article/details/87000143

你可能感兴趣的:(python)