精华内容
下载资源
问答
  • 今天小编就为大家分享一篇关于Python使用folium excel绘制point,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
  • 基于这两个平台,博主进行了一系列的开发研究工作,本文介绍其中一项技术,如何用folium包绘制城市道路图,当然,也可绘制非城市道路图,只要提供正确的路名就行了。 开发工具: Python3.7 Spyder编译器(也可以...
  • 主要为大家详细介绍了python使用folium库绘制地图点击框,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • 当前,定义了一种方法folium_static() ,该方法采用folium.Map或folium.Figure对象并将其显示在Streamlit应用程序中。 安装 pip install streamlit - folium or conda install - c conda - forge streamlit - ...
  • 各类速查表汇总-Folium

    2019-04-10 08:50:19
    各类速查表汇总-Folium open-source JavaScript library for mobile-friendly interactive maps Python 人工智能
  • 这是纽约市开放数据周活动“如何使用Folium创建地图”的存储库。 该活动将于2021年3月12日星期五晚上7点举行。 该存储库包括此事件所需的数据集,shapefile和IPython工作簿。 该项目提供了有关如何使用Python GIS...
  • 今天小编就为大家分享一篇Python 使用folium绘制leaflet地图的实现方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • 一个准系统的Flask应用程序,它使用WMATA API演示了一些基本的Folium功能。 此确切的存储库托管在Heroku的。 它采用了一个演示示例,并展示了如何通过Web浏览器进行交付。 该代码旨在展示可能性,而不是最佳实践。 ...
  • 目录数据集介绍可视化步骤1. 导入pandas等需要的库2. 读取数据,查看基本情况3. 读取城市坐标数据4. 按省份统计人数5. 合并城市坐标数据 与 省份数据6.... 数据集介绍 1.100000_full.json (地理位置数据集,用于绘制...
  • folium html src.zip

    2021-10-26 12:28:29
    folium库使用的js脚本文件包,在无法链接js服务器,或者链接缓慢时,可以使用离线包加快html文件的加载速度
  • 地图可视化组件–folium简单介绍 folium是基于Python环境开发的一个地图绘制包,可以在程序中引入从而绘制精美的地图数据可视化图表。folium建立在Python生态系统的数据处理能力和Leaflet.js库的映射能力之上。 用...
  • 使用Folium&Bokeh可视化地理数据 PyLadies LA的存储库合作者和联合组织者:Sylvia Tran(大叶)+ Emma Freeman(散景) PyLadies Los Angeles 2018年6月21日聚会 此回购演示叶和背景虚化库以可视化地理数据。 大叶...
  • folium建立在Python生态系统的数据处理能力和Leaflet.js库的映射能力之上。 用Python处理数据,然后通过叶在可视化的Leaflet贴图中显示。 安装 $ pip install folium 或者 $ conda install -c conda-forge folium ...
  • folium-源码

    2021-03-14 23:30:04
    folium
  • Folium

    2021-12-03 10:51:49
    Python地图可视化之Folium – 标点符

    Python地图可视化之Folium – 标点符

    Quickstart — Folium 0.12.1 documentation

    有关于json文件的读取问题:
    Python可视化笔记之folium交互地图 - 知乎

    Folium保存为html文件后,重新读入:

    self.mapHtml.load(QUrl.fromLocalFile(rf'{stationMap_path}\{select_province}.html'))

    mapHtml 是 html 解释器,比如 pyqt5 的 QWebEngineView 控件
    html文件中会保存中心坐标等信息,所以可以在显示前先保存到中心再显示

    颜控+轻便——借助Folium实现动态热力图绘制 - 知乎
    heatmap 有点问题,不能如实的反应aqi实际数值大小。gradient中的数字代表百分位数,也就是说heatmap是根据数据密度来作图的,和数据本身的数值无关






     

    展开全文
  • Folium TutorialsGenerating Maps with PythonObjectivesIntroductionTable of ContentsExploring Datasets with _pandas_ and MatplotlibDownloading and Prepping Data Introduction to Folium Let's install **...

    more about Pandas入门 DataFrame的常用函数

    Generating Maps with Python

    Objectives

    After completing this lab you will be able to:

    • Visualize geospatial data with Folium

    Introduction

    In this lab, we will learn how to create maps for different objectives. To do that, we will part ways with Matplotlib and work with another Python visualization library, namely Folium. What is nice about Folium is that it was developed for the sole purpose of visualizing geospatial data. While other libraries are available to visualize geospatial data, such as plotly, they might have a cap on how many API calls you can make within a defined time frame. Folium, on the other hand, is completely free.

    Table of Contents

    1. Exploring Datasets with _p_andas
    2. Downloading and Prepping Data
    3. Introduction to Folium
    4. Map with Markers
    5. Choropleth Maps

    Exploring Datasets with pandas and Matplotlib

    Toolkits: This lab heavily relies on pandas and Numpy for data wrangling, analysis, and visualization. The primary plotting library we will explore in this lab is Folium.

    Datasets:

    1. San Francisco Police Department Incidents for the year 2016 - Police Department Incidents from San Francisco public data portal. Incidents derived from San Francisco Police Department (SFPD) Crime Incident Reporting system. Updated daily, showing data for the entire year of 2016. Address and location has been anonymized by moving to mid-block or to an intersection.

    2. Immigration to Canada from 1980 to 2013 - International migration flows to and from selected countries - The 2015 revision from United Nation’s website. The dataset contains annual data on the flows of international migrants as recorded by the countries of destination. The data presents both inflows and outflows according to the place of birth, citizenship or place of previous / next residence both for foreigners and nationals. For this lesson, we will focus on the Canadian Immigration data

    Downloading and Prepping Data

    Import Primary Modules:

    import numpy as np  # useful for many scientific computing in Python
    import pandas as pd # primary data structure library
    

    Introduction to Folium

    Folium is a powerful Python library that helps you create several types of Leaflet maps. The fact that the Folium results are interactive makes this library very useful for dashboard building.

    From the official Folium documentation page:

    Folium builds on the data wrangling strengths of the Python ecosystem and the mapping strengths of the Leaflet.js library. Manipulate your data in Python, then visualize it in on a Leaflet map via Folium.

    Folium makes it easy to visualize data that’s been manipulated in Python on an interactive Leaflet map. It enables both the binding of data to a map for choropleth visualizations as well as passing Vincent/Vega visualizations as markers on the map.

    The library has a number of built-in tilesets from OpenStreetMap, Mapbox, and Stamen, and supports custom tilesets with Mapbox or Cloudmade API keys. Folium supports both GeoJSON and TopoJSON overlays, as well as the binding of data to those overlays to create choropleth maps with color-brewer color schemes.

    Let’s install Folium

    Folium is not available by default. So, we first need to install it before we are able to import it.

    # !conda install -c conda-forge folium=0.5.0 --yes
    # !pip install folium
    import folium
    
    print('Folium installed and imported!')
    
    folium.Map(location=[-40.4637, -3.7492], zoom_start=6, tiles='Stamen Toner')
    

    Generating the world map is straigtforward in Folium. You simply create a Folium Map object and then you display it. What is attactive about Folium maps is that they are interactive, so you can zoom into any region of interest despite the initial zoom level.

    # define the world map
    world_map = folium.Map()
    
    # display world map
    world_map
    

    Go ahead. Try zooming in and out of the rendered map above.

    You can customize this default definition of the world map by specifying the centre of your map and the intial zoom level.

    All locations on a map are defined by their respective Latitude and Longitude values. So you can create a map and pass in a center of Latitude and Longitude values of [0, 0].

    For a defined center, you can also define the intial zoom level into that location when the map is rendered. The higher the zoom level the more the map is zoomed into the center.

    Let’s create a map centered around Canada and play with the zoom level to see how it affects the rendered map.

    # define the world map centered around Canada with a low zoom level
    world_map = folium.Map(location=[56.130, -106.35], zoom_start=4)
    
    # display world map
    world_map
    

    Let’s create the map again with a higher zoom level

    # define the world map centered around Canada with a higher zoom level
    world_map = folium.Map(location=[56.130, -106.35], zoom_start=8)
    
    # display world map
    world_map
    

    As you can see, the higher the zoom level the more the map is zoomed into the given center.

    Question: Create a map of Mexico with a zoom level of 4.

    ### type your answer here
    
    
    #define Mexico's geolocation coordinates
    mexico_latitude = 23.6345 
    mexico_longitude = -102.5528
    
    # define the world map centered around Canada with a higher zoom level
    mexico_map = folium.Map(location=[mexico_latitude, mexico_longitude], zoom_start=4)
    
    # display world map
    mexico_map
    
    Click here for a sample python solution
        #The correct answer is:
        
        #define Mexico's geolocation coordinates
        mexico_latitude = 23.6345 
        mexico_longitude = -102.5528
    
        # define the world map centered around Canada with a higher zoom level
        mexico_map = folium.Map(location=[mexico_latitude, mexico_longitude], zoom_start=4)
    
        # display world map
        mexico_map
    
    

    Another cool feature of Folium is that you can generate different map styles.

    A. Stamen Toner Maps

    These are high-contrast B+W (black and white) maps. They are perfect for data mashups and exploring river meanders and coastal zones.

    Let’s create a Stamen Toner map of canada with a zoom level of 4.

    # create a Stamen Toner map of the world centered around Canada
    world_map = folium.Map(location=[56.130, -106.35], zoom_start=4, tiles='Stamen Toner')
    
    # display map
    world_map
    

    Feel free to zoom in and out to see how this style compares to the default one.

    B. Stamen Terrain Maps

    These are maps that feature hill shading and natural vegetation colors. They showcase advanced labeling and linework generalization of dual-carriageway roads.

    Let’s create a Stamen Terrain map of Canada with zoom level 4.

    # create a Stamen Toner map of the world centered around Canada
    world_map = folium.Map(location=[56.130, -106.35], zoom_start=4, tiles='Stamen Terrain')
    
    # display map
    world_map
    

    Feel free to zoom in and out to see how this style compares to Stamen Toner and the default style.

    Zoom in and notice how the borders start showing as you zoom in, and the displayed country names are in English.

    Question: Create a map of Mexico to visualize its hill shading and natural vegetation. Use a zoom level of 6.

    ### type your answer here
    
    #define Mexico's geolocation coordinates
    mexico_latitude = 23.6345 
    mexico_longitude = -102.5528
    
    # define the world map centered around Canada with a higher zoom level
    mexico_map = folium.Map(location=[mexico_latitude, mexico_longitude], zoom_start=6, tiles='Stamen Terrain')
    
    # display world map
    mexico_map
    
    Click here for a sample python solution
        #The correct answer is:
        
        #define Mexico's geolocation coordinates
        mexico_latitude = 23.6345 
        mexico_longitude = -102.5528
    
        # define the world map centered around Canada with a higher zoom level
        mexico_map = folium.Map(location=[mexico_latitude, mexico_longitude], zoom_start=6, tiles='Stamen Terrain')
    
        # display world map
        mexico_map
    
    

    Maps with Markers

    Let’s download and import the data on police department incidents using pandas read_csv() method.

    Download the dataset and read it into a pandas dataframe:

    df_incidents = pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/Police_Department_Incidents_-_Previous_Year__2016_.csv')
    
    print('Dataset downloaded and read into a pandas dataframe!')
    

    Let’s take a look at the first five items in our dataset.

    df_incidents.head()
    

    So each row consists of 13 features:

    1. IncidntNum: Incident Number
    2. Category: Category of crime or incident
    3. Descript: Description of the crime or incident
    4. DayOfWeek: The day of week on which the incident occurred
    5. Date: The Date on which the incident occurred
    6. Time: The time of day on which the incident occurred
    7. PdDistrict: The police department district
    8. Resolution: The resolution of the crime in terms whether the perpetrator was arrested or not
    9. Address: The closest address to where the incident took place
    10. X: The longitude value of the crime location
    11. Y: The latitude value of the crime location
    12. Location: A tuple of the latitude and the longitude values
    13. PdId: The police department ID

    Let’s find out how many entries there are in our dataset.

    df_incidents.shape
    

    So the dataframe consists of 150,500 crimes, which took place in the year 2016. In order to reduce computational cost, let’s just work with the first 100 incidents in this dataset.

    # get the first 100 crimes in the df_incidents dataframe
    limit = 100
    df_incidents = df_incidents.iloc[0:limit, :]
    

    Let’s confirm that our dataframe now consists only of 100 crimes.

    df_incidents.shape
    

    Now that we reduced the data a little bit, let’s visualize where these crimes took place in the city of San Francisco. We will use the default style and we will initialize the zoom level to 12.

    # San Francisco latitude and longitude values
    latitude = 37.77
    longitude = -122.42
    
    # create map and display it
    sanfran_map = folium.Map(location=[latitude, longitude], zoom_start=12)
    
    # display the map of San Francisco
    sanfran_map
    

    Now let’s superimpose the locations of the crimes onto the map. The way to do that in Folium is to create a feature group with its own features and style and then add it to the sanfran_map.

    # instantiate a feature group for the incidents in the dataframe
    incidents = folium.map.FeatureGroup()
    
    # loop through the 100 crimes and add each to the incidents feature group
    for lat, lng, in zip(df_incidents.Y, df_incidents.X):
        incidents.add_child(
            folium.CircleMarker(
                [lat, lng],
                radius=5, # define how big you want the circle markers to be
                color='yellow',
                fill=True,
                fill_color='blue',
                fill_opacity=0.6
            )
        )
    
    # add incidents to map
    sanfran_map.add_child(incidents)
    

    You can also add some pop-up text that would get displayed when you hover over a marker. Let’s make each marker display the category of the crime when hovered over.

    # instantiate a feature group for the incidents in the dataframe
    incidents = folium.map.FeatureGroup()
    
    # loop through the 100 crimes and add each to the incidents feature group
    for lat, lng, in zip(df_incidents.Y, df_incidents.X):
        incidents.add_child(
            folium.CircleMarker(
                [lat, lng],
                radius=5, # define how big you want the circle markers to be
                color='yellow',
                fill=True,
                fill_color='blue',
                fill_opacity=0.6
            )
        )
    
    # add pop-up text to each marker on the map
    latitudes = list(df_incidents.Y)
    longitudes = list(df_incidents.X)
    labels = list(df_incidents.Category)
    
    for lat, lng, label in zip(latitudes, longitudes, labels):
        folium.Marker([lat, lng], popup=label).add_to(sanfran_map)    
        
    # add incidents to map
    sanfran_map.add_child(incidents)
    

    Isn’t this really cool? Now you are able to know what crime category occurred at each marker.

    If you find the map to be so congested will all these markers, there are two remedies to this problem. The simpler solution is to remove these location markers and just add the text to the circle markers themselves as follows:

    # create map and display it
    sanfran_map = folium.Map(location=[latitude, longitude], zoom_start=12)
    
    # loop through the 100 crimes and add each to the map
    for lat, lng, label in zip(df_incidents.Y, df_incidents.X, df_incidents.Category):
        folium.CircleMarker(
            [lat, lng],
            radius=5, # define how big you want the circle markers to be
            color='yellow',
            fill=True,
            popup=label,
            fill_color='blue',
            fill_opacity=0.6
        ).add_to(sanfran_map)
    
    # show map
    sanfran_map
    

    The other proper remedy is to group the markers into different clusters. Each cluster is then represented by the number of crimes in each neighborhood. These clusters can be thought of as pockets of San Francisco which you can then analyze separately.

    To implement this, we start off by instantiating a MarkerCluster object and adding all the data points in the dataframe to this object.

    from folium import plugins
    
    # let's start again with a clean copy of the map of San Francisco
    sanfran_map = folium.Map(location = [latitude, longitude], zoom_start = 12)
    
    # instantiate a mark cluster object for the incidents in the dataframe
    incidents = plugins.MarkerCluster().add_to(sanfran_map)
    
    # loop through the dataframe and add each data point to the mark cluster
    for lat, lng, label, in zip(df_incidents.Y, df_incidents.X, df_incidents.Category):
        folium.Marker(
            location=[lat, lng],
            icon=None,
            popup=label,
        ).add_to(incidents)
    
    # display map
    sanfran_map
    

    Notice how when you zoom out all the way, all markers are grouped into one cluster, the global cluster, of 100 markers or crimes, which is the total number of crimes in our dataframe. Once you start zooming in, the global cluster will start breaking up into smaller clusters. Zooming in all the way will result in individual markers.

    Choropleth Maps

    A Choropleth map is a thematic map in which areas are shaded or patterned in proportion to the measurement of the statistical variable being displayed on the map, such as population density or per-capita income. The choropleth map provides an easy way to visualize how a measurement varies across a geographic area or it shows the level of variability within a region. Below is a Choropleth map of the US depicting the population by square mile per state.

    Now, let’s create our own Choropleth map of the world depicting immigration from various countries to Canada.

    Let’s first download and import our primary Canadian immigration dataset using pandas read_excel() method. Normally, before we can do that, we would need to download a module which pandas requires to read in excel files. This module is xlrd. For your convenience, we have pre-installed this module, so you would not have to worry about that. Otherwise, you would need to run the following line of code to install the xlrd module:

    !conda install -c anaconda xlrd --yes
    

    Download the dataset and read it into a pandas dataframe:

    df_can = pd.read_excel('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/Canada.xlsx',
                         sheet_name='Canada by Citizenship',
                         skiprows=range(20),
                         skipfooter=2)
    
    print('Data downloaded and read into a dataframe!')
    

    Let’s take a look at the first five items in our dataset.

    df_can.head()
    

    Let’s find out how many entries there are in our dataset.

    # print the dimensions of the dataframe
    print(df_can.shape)
    

    Clean up data. We will make some modifications to the original dataset to make it easier to create our visualizations. Refer to Introduction to Matplotlib and Line Plots and Area Plots, Histograms, and Bar Plots notebooks for a detailed description of this preprocessing.

    # clean up the dataset to remove unnecessary columns (eg. REG) 
    df_can.drop(['AREA','REG','DEV','Type','Coverage'], axis=1, inplace=True)
    
    # let's rename the columns so that they make sense
    df_can.rename(columns={'OdName':'Country', 'AreaName':'Continent','RegName':'Region'}, inplace=True)
    
    # for sake of consistency, let's also make all column labels of type string
    df_can.columns = list(map(str, df_can.columns))
    
    # add total column
    df_can['Total'] = df_can.sum(axis=1)
    
    # years that we will be using in this lesson - useful for plotting later on
    years = list(map(str, range(1980, 2014)))
    print ('data dimensions:', df_can.shape)
    

    Let’s take a look at the first five items of our cleaned dataframe.

    df_can.head()
    

    In order to create a Choropleth map, we need a GeoJSON file that defines the areas/boundaries of the state, county, or country that we are interested in. In our case, since we are endeavoring to create a world map, we want a GeoJSON that defines the boundaries of all world countries. For your convenience, we will be providing you with this file, so let’s go ahead and download it. Let’s name it world_countries.json.

    # download countries geojson file
    !wget --quiet https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/world_countries.json
        
    print('GeoJSON file downloaded!')
    

    Now that we have the GeoJSON file, let’s create a world map, centered around [0, 0] latitude and longitude values, with an intial zoom level of 2.

    world_geo = r'world_countries.json' # geojson file
    
    # create a plain world map
    world_map = folium.Map(location=[0, 0], zoom_start=2)
    

    And now to create a Choropleth map, we will use the choropleth method with the following main parameters:

    1. geo_data, which is the GeoJSON file.
    2. data, which is the dataframe containing the data.
    3. columns, which represents the columns in the dataframe that will be used to create the Choropleth map.
    4. key_on, which is the key or variable in the GeoJSON file that contains the name of the variable of interest. To determine that, you will need to open the GeoJSON file using any text editor and note the name of the key or variable that contains the name of the countries, since the countries are our variable of interest. In this case, name is the key in the GeoJSON file that contains the name of the countries. Note that this key is case_sensitive, so you need to pass exactly as it exists in the GeoJSON file.
    # generate choropleth map using the total immigration of each country to Canada from 1980 to 2013
    world_map.choropleth(
        geo_data=world_geo,
        data=df_can,
        columns=['Country', 'Total'],
        key_on='feature.properties.name',
        fill_color='YlOrRd', 
        fill_opacity=0.7, 
        line_opacity=0.2,
        legend_name='Immigration to Canada'
    )
    
    # display map
    world_map
    

    As per our Choropleth map legend, the darker the color of a country and the closer the color to red, the higher the number of immigrants from that country. Accordingly, the highest immigration over the course of 33 years (from 1980 to 2013) was from China, India, and the Philippines, followed by Poland, Pakistan, and interestingly, the US.

    Notice how the legend is displaying a negative boundary or threshold. Let’s fix that by defining our own thresholds and starting with 0 instead of -6,918!

    world_geo = r'world_countries.json'
    
    # create a numpy array of length 6 and has linear spacing from the minium total immigration to the maximum total immigration
    threshold_scale = np.linspace(df_can['Total'].min(),
                                  df_can['Total'].max(),
                                  6, dtype=int)
    threshold_scale = threshold_scale.tolist() # change the numpy array to a list
    threshold_scale[-1] = threshold_scale[-1] + 1 # make sure that the last value of the list is greater than the maximum immigration
    
    # let Folium determine the scale.
    world_map = folium.Map(location=[0, 0], zoom_start=2)
    world_map.choropleth(
        geo_data=world_geo,
        data=df_can,
        columns=['Country', 'Total'],
        key_on='feature.properties.name',
        threshold_scale=threshold_scale,
        fill_color='YlOrRd', 
        fill_opacity=0.7, 
        line_opacity=0.2,
        legend_name='Immigration to Canada',
        reset=True
    )
    world_map
    

    Much better now! Feel free to play around with the data and perhaps create Choropleth maps for individuals years, or perhaps decades, and see how they compare with the entire period from 1980 to 2013.

    展开全文
  • 在 Python 和 Folium 的帮助下,可视化美国的活跃火山。 此外,创建一个区域分布图来展示同一国家的失业率。 1. 安装依赖 安装依赖项是您要做的第一件事。 #Library Management Package sudo apt install python3-...
  • 大叶 简单的图像滑块。 。
  • Folium是一个功能强大的Python库,可帮助您创建几种类型的Leaflet映射。 ...要想出主意,只需缩放/单击下一张地图即可获得印象。 文献资料 先决条件: Python folium 安装: $ pip install folium 要么 $ conda ...
  • Python软件包:flask,pymysql,wtforms,pass_lib,folium,ipywidgets 要运行该应用程序,请执行以下步骤: 确保使用以下命令安装所有软件包。 >> python -r requirements.txt 在MySql中创建一个数据库并使用...
  • Python绘制地图神器folium入门

    千次阅读 2021-01-29 13:37:57
    二、安装方法 按照官方的教程即可,如果安装了 conda ,可以直接 conda install -c conda-forge folium 没有安装的话就使用 python3 -m pip install folium 三、主要功能 3.1 各级别地图 folium 显示地图的类为 ...

    文章目录

    一、简介

    二、安装方法

    三、主要功能

    3.1 各级别地图

    3.1.1 世界地图

    3.1.2 国家地图

    3.1.3 市级地图

    3.2 地图形式

    3.3 在地图上标记

    3.3.1 普通标记

    3.3.2 点击获取经纬度

    3.3.3 动态放置标记

    3.4 热力图绘制

    3.5 密度地图绘制

    3.6 自定义地图区域

    3.6.1 只绘制边界,不添加数据

    3.6.2 绘制边界,添加数据

    四、竞品对比与优劣势

    五、参考资料

    一、简介

    想通过 Python 绘制精美的地图?想在地图上自由的设置各种参数?想获得灵活的交互体验?这里就有一款Python 神包满足你:folium。

    folium 建立在 Python 生态系统的数据应用能力和 Leaflet.js 库的映射能力之上,在Python中操作数据,然后通过 folium 在 Leaflet 地图中可视化。

    folium 相比较于国内百度的 pyecharts 灵活性更强,能够自定义绘制区域,并且展现形式更加多样化。

    附:官方文档,官方示例,本文 notebook ,完整代码及数据。

    二、安装方法

    按照官方的教程即可,如果安装了 conda ,可以直接

    conda install -c conda-forge folium

    没有安装的话就使用

    python3 -m pip install folium

    三、主要功能

    3.1 各级别地图

    folium 显示地图的类为 folium.Map,类的声明如下

    class folium.folium.Map(location=None, width='100%', height='100%', left='0%', top='0%', position='relative', tiles='OpenStreetMap', attr=None, min_zoom=0, max_zoom=18, zoom_start=10, min_lat=-90, max_lat=90, min_lon=-180, max_lon=180, max_bounds=False, crs='EPSG3857', control_scale=False, prefer_canvas=False, no_touch=False, disable_3d=False, png_enabled=False, zoom_control=True, **kwargs)

    讲几个重要的参数

    location 经纬度,list 或者 tuple 格式,顺序为 latitude, longitude

    zoom_start 缩放值,默认为 10,值越大比例尺越小,地图放大级别越大

    tiles 显示样式,默认*‘OpenStreetMap’*,也就是开启街道显示

    crs 地理坐标参考系统,默认为"EPSG3857"

    3.1.1 世界地图

    import folium

    print(folium.__version__)

    # define the world map

    world_map = folium.Map()

    # display world map

    world_map

    158f892ccdee7b7c9b127ec1ccc21c08.png

    3.1.2 国家地图

    # define the national map

    national_map = folium.Map(location=[35.3, 100.6], zoom_start=4)

    # display national map

    national_map

    655f7cd00027a759cef49b7a4ee717bc.png

    3.1.3 市级地图

    其实改变地图显示就是改变显示的经纬度和缩放比例,省级、市级、县级用法雷同,这里举一个市级的例子为例,如北京市:

    # define the city map

    city_map = folium.Map(location=[39.93, 116.40], zoom_start=10)

    # display city map

    city_map

    4104f00642590c655759c9e4be8af7e8.png

    显示效果确实是不如百度的。

    3.2 地图形式

    除了上述正常的地图显示外,folium 还提供了非常丰富的多样化显示,控制显示效果的变量是tiles,样式有OpenStreetMap, Stamen Terrain, Stamen Toner, Mapbox Bright, Mapbox Control Room等等,这里挑选几个比较常见的

    # define the city map,tiles='Stamen Toner'

    city_map = folium.Map(location=[39.93, 116.40], zoom_start=10, tiles='Stamen Toner')

    # display city map

    city_map

    # define the city map, tiles='Stamen Terrain'

    city_map = folium.Map(location=[39.93, 116.40], zoom_start=10, tiles='Stamen Terrain')

    # display city map

    city_map

    f6c52a4b4aa6b332ee276396b937eb25.png

    3.3 在地图上标记

    3.3.1 普通标记

    添加普通标记用 Marker

    这里可以选择标记的图案。

    bj_map = folium.Map(location=[39.93, 115.40], zoom_start=12, tiles='Stamen Terrain')

    folium.Marker(

    location=[39.95, 115.33],

    popup='Mt. Hood Meadows',

    icon=folium.Icon(icon='cloud')

    ).add_to(bj_map)

    folium.Marker(

    location=[39.96, 115.32],

    popup='Timberline Lodge',

    icon=folium.Icon(color='green')

    ).add_to(bj_map)

    folium.Marker(

    location=[39.93, 115.34],

    popup='Some Other Location',

    icon=folium.Icon(color='red', icon='info-sign')

    ).add_to(bj_map)

    bj_map

    137fc3cc22d0e160d70c81c73d25b7e5.png

    添加圆形标记用 Circle 以及 CircleMarker

    bj_map = folium.Map(location=[39.93, 116.40], zoom_start=12, tiles='Stamen Toner')

    folium.Circle(

    radius=200,

    location=[39.92, 116.43],

    popup='The Waterfront',

    color='crimson',

    fill=False,

    ).add_to(bj_map)

    folium.CircleMarker(

    location=[39.93, 116.38],

    radius=50,

    popup='Laurelhurst Park',

    color='#3186cc',

    fill=True,

    fill_color='#3186cc'

    ).add_to(bj_map)

    bj_map

    3775e6cf3f6bdc2698460a4dc1eb05e5.png

    3.3.2 点击获取经纬度

    m = folium.Map(location=[46.1991, -122.1889],tiles='Stamen Terrain',zoom_start=13)

    m.add_child(folium.LatLngPopup())

    m

    通过点击鼠标便可以获取点击出的经纬度。

    3.3.3 动态放置标记

    m = folium.Map(

    location=[46.8527, -121.7649],

    tiles='Stamen Terrain',

    zoom_start=13

    )

    folium.Marker(

    [46.8354, -121.7325],

    popup='Camp Muir'

    ).add_to(m)

    m.add_child(folium.ClickForMarker(popup='Waypoint'))

    m

    3.4 热力图绘制

    因为没有实际的经纬度坐标数据,所以这里只能模拟一些位置出来,另外每个位置还需要一个数值作为热力值。

    # generated data

    import numpy as np

    data = (

    np.random.normal(size=(100, 3)) *

    np.array([[0.1, 0.1, 0.1]]) +

    np.array([[40, 116.5, 1]])

    ).tolist()

    data[:3]

    数据分布

    [[40.04666663299843, 116.59569796477264, 0.9667425547098781],

    [39.86836537517533, 116.28201445195315, 0.8708549157348728],

    [40.08123232852134, 116.56884585184197, 0.9104952244371285]]

    绘制热力图

    # HeatMap

    from folium.plugins import HeatMap

    m = folium.Map([39.93, 116.38], tiles='stamentoner', zoom_start=6)

    HeatMap(data).add_to(m)

    # m.save(os.path.join('results', 'Heatmap.html'))

    m

    095726c9f6c634ab02ca271a166ad490.png

    3.5 密度地图绘制

    folium 不仅可以绘制热力图,还可以绘制密度地图,按照经纬度进行举例聚类,然后在地图中显示。

    from folium.plugins import MarkerCluster

    m = folium.Map([39.93, 116.38], tiles='stamentoner', zoom_start=10)

    # create a mark cluster object

    marker_cluster = MarkerCluster().add_to(m)

    # add data point to the mark cluster

    for lat, lng, label in data:

    folium.Marker(

    location=[lat, lng],

    icon=None,

    popup=label,

    ).add_to(marker_cluster)

    # add marker_cluster to map

    m.add_child(marker_cluster)

    7e697fc320caa58108b6b64c07fd3a16.png

    3.6 自定义地图区域

    folium 一个非常有优势的功能就是自定义区域的绘制了,只要有区域的边界数据,就可以在地图中以多种多样的形式展现出来,这里以 folium 官方的美国地图为例,源数据是一个 .json 文件,里面包含了各个地区(美国各州)的特征(包括边界经纬度列表、简称等),源数据传送门,其数据格式如下:

    96af3e08d0087c96343c4eb49d2da8c0.png

    3.6.1 只绘制边界,不添加数据

    如果只要求绘制边界,而不显示边界区域的相关信息,那么这个是比较容易的,代码如下

    import json

    import requests

    # read us-states border

    with open("us-states.json") as f:

    us_states = json.load(f)

    us_map = folium.Map(location=[35.3, -97.6], zoom_start=4)

    folium.GeoJson(

    us_states,

    style_function=lambda feature: {

    'fillColor': '#ffff00',

    'color': 'black',

    'weight': 2,

    'dashArray': '5, 5'

    }

    ).add_to(us_map)

    #display map

    us_map

    dcc2a095f8b430682526edc06290a3a3.png

    3.6.2 绘制边界,添加数据

    当需要在各个区域填充数据的时候,这个稍微麻烦点,不仅需要各个区域的边界数据,还需要各个区域的显示信息,这里同样也使用官方的美国各州的边界数据为例:

    import geopandas as gpd

    import pandas as pd

    import folium, branca

    states = gpd.GeoDataFrame.from_features(us_states, crs=fiona.crs.from_epsg(4326))

    states.head()

    2d606776d8ff190e3b0615bc995457f6.png

    我们再把收入等数据连接到上表中

    abbrs = pd.read_json(open("abbrs.json"))

    statesmerge = states.merge(abbrs,how='left', left_on='name', right_on='name')

    statesmerge['geometry']=statesmerge.geometry.simplify(.05)

    income = pd.read_csv("income.csv", dtype={"fips":str})

    income['income-2015']=pd.to_numeric(income['income-2015'], errors='coerce')

    income.groupby(by="state")[['state','income-2015']].median().head()

    statesmerge['medianincome']=statesmerge.merge(income.groupby(by="state")[['state','income-2015']].median(), how='left', left_on='alpha-2', right_on='state')['income-2015']

    statesmerge['change']=statesmerge.merge(income.groupby(by="state")[['state','change']].median(), how='left', left_on='alpha-2', right_on='state')['change']

    statesmerge.head()

    08af37d50ea82a238409ba1c4069b9e7.png

    最终绘制出的来的地图如下:

    除此之外,还有很多非常有趣的功能,这里就不一一列举了,感兴趣的可以参考官方的文档。

    四、竞品对比与优劣势

    国内的竞品为百度的 pyecharts,和 folium 一样都可以实现普通的地图绘制功能,但是具体使用还有较大的区别,具体如下表

    功能

    pyecharts

    folium

    备注

    世界地图

    可以

    可以

    中文显示

    可以

    部分可以

    folium地图中标尺、文字不能正常显示,但是嵌入地图中的中文可以正常显示

    交互性

    区(县)级地图

    可以

    可以

    folium需要区(县)边界数据

    市级地图

    可以

    可以

    folium需要市边界数据

    收费

    自定义区域需要购买百度ak

    自定义区域功能免费

    灵活性

    省级地图

    可以

    可以

    folium需要省边界数据

    美观度

    较好

    自定义区域

    部分可以

    可以

    pyecharts需要百度 ak,folium免费

    五、参考资料

    [1] https://www.zhihu.com/question/33783546

    [2] https://pypi.org/project/folium/

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

    展开全文
  • 纽约市的社区分割与聚类 该项目旨在使用Foursquare API探索纽约市的社区,以获取每个社区中最常见的场所类别,然后使用此功能将社区分组。... 最后,我们将使用Folium库来可视化纽约市的社区及其新兴集群。
  • 今天跟大家介绍一下如何使用folium更换地图底图样式 1. 准备工作 有朋友可能没用过folium,它其实就是python的一个专业绘制地图的第三方库,所以在使用之前需要先安装它。 pipinstallfolium 在安装完成...

    今天跟大家介绍一下如何使用folium更换地图底图样式

    1. 准备工作

    有朋友可能没用过folium,它其实就是python的一个专业绘制地图的第三方库,所以在使用之前需要先安装它。

    pip install folium
    

    在安装完成之后,我们可以在jupyterlab进行演示如下:

    import folium
    
    m = folium.Map()
    m
    

    图片

    默认

    对于上面的输出,其实是一个可交互的地图,支持放大缩写拖拽等等。

    如果你想将输出存在本地,可以这样来:

    m.save('map.html')
    

    可以看到本地就存了这个一个文件,浏览器打开就可以进行交互式操作了。

    图片

    map文件

    以上就是一个平平淡淡的过程......

    2. 关于folium.Map()

    在上一部分我们可以看到这个map玩意直接就是一个地图啦,这里我们就介绍一下它常用的几个参数。

    folium.Map(
        location=None,
        width='100%',
        height='100%',
        left='0%',
        top='0%',
        position='relative',
        tiles='OpenStreetMap',
        attr=None,
        min_zoom=0,
        max_zoom=18,
        zoom_start=10,
        min_lat=-90,
        max_lat=90,
        min_lon=-180,
        max_lon=180,
        max_bounds=False,
        crs='EPSG3857',
        control_scale=False,
        prefer_canvas=False,
        no_touch=False,
        disable_3d=False,
        png_enabled=False,
        zoom_control=True,
        **kwargs,
    )
    

    参数可真多啊!!

    没有参数的folium.Map()将得到一张世界地图。

    • location:地图中心,[40.002694, 116.322373]是清华大学校区;

    • zoom_start:比例尺,默认为10级,大约是一个城市的范围;

    其他常用参数包括:

    • widthheight:地图的长宽,如果是int则表示像素值,如果是str则表示百分比;

    • max_zoom:地图可以手动调节的最大比例,默认为18级;

    • control_scale:是否在地图上添加比例尺,默认为False;

    • no_touch:是否禁止手动操作,默认为False;

    • tiles:地图样式,默认为OpenStreetMap

    • attr:如果设置非内建地图样式,则需要传入这个值,可以理解为你选择的地图样式名称

    以上是常用的一些参数,而最常用的莫过于 locationzoom_starttiles等。

    内建地图样式还有一下几种:

    - "OpenStreetMap"
    - "Mapbox Bright" (Limited levels of zoom for free tiles)
    - "Mapbox Control Room" (Limited levels of zoom for free tiles)
    - "Stamen" (Terrain, Toner, and Watercolor)
    - "Cloudmade" (Must pass API key)
    - "Mapbox" (Must pass API key)
    - "CartoDB" (positron and dark_matter)
    

    我们简单试下locationzoo_start参数:

    import folium
    
    m = folium.Map([40.002694, 116.322373],
                   zoom_start=15,
                   control_scale=True
                  )
    m
    

    可以看到清华大学校区

    图片

    清华大学校区

    以上对Map的参数进行了简单的介绍,接下来,我们就来看看地图底图样式的选取情况吧~

    3. 内建地图底图样式

    我们看到folium其实有好几种内建地图底图样式,其中部分需要去申请key,由于我这边没有申请成功就不做演示了。

    • "OpenStreetMap"

    • "Mapbox Bright" (Limited levels of zoom for free tiles)

    • "Mapbox Control Room" (Limited levels of zoom for free tiles)

    • "Stamen" (Terrain, Toner, and Watercolor)

    • "Cloudmade" (Must pass API key)

    • "Mapbox" (Must pass API key)

    • "CartoDB" (positron and dark_matter)

    地势地形底图

    m = folium.Map([40.002694, 116.322373],
                   tiles='Stamen Terrain',
                   zoom_start=15,
                   control_scale=True
                  )
    m
    

    图片

    黑白无标记底图

    m = folium.Map([40.002694, 116.322373],
                   tiles='Stamen Toner',
                   zoom_start=15,
                   control_scale=True
                  )
    m
    

    图片

    水墨画底图

    m = folium.Map([40.002694, 116.322373],
                   tiles='Stamen Watercolor',
                   zoom_start=15,
                   control_scale=True
                  )
    m
    

    图片

    以上就是内建地图底图样式的一些展示,部分需要key的大家可以去这个网站申请:

    http://openwhatevermap.xyz/(可惜我上不去)

    另外,在这里也可以找到一些地图底图

    http://leaflet-extras.github.io/leaflet-providers/preview/

    我后续也会去研究这些地图底图样式,试着分享更多有趣的地图分享给大家。

    当然了,国内咱们用的较多的地图是高德、百度和腾讯地图等,接下来我们就来玩玩!

    4. 多种第三方地图底图样式

    这里我将演示高德地图、智图GeoQ和腾讯地图等

    4.1. 高德地图

    高德地图的 中英文地图、卫星影像图、街道图与常规图

    中英文地图

    folium.Map([40.002694, 116.322373],
               tiles='https://webrd02.is.autonavi.com/appmaptile?lang=zh_en&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
               attr='高德-中英文对照',
               zoom_start=15,
              )
    

    图片

    纯英文地图

    folium.Map([40.002694, 116.322373],
               tiles='https://webrd02.is.autonavi.com/appmaptile?lang=en&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
               attr='高德-纯英文对照',
               zoom_start=15,
              )
    

    图片

    卫星影像图

    tiles = 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'
    folium.Map([40.002694, 116.322373],
               tiles= tiles,
               attr='高德-卫星影像图',
               zoom_start=15,
              )
    

    图片

    街道图
    
    folium.Map([40.002694, 116.322373],
               tiles= 'https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8&ltype=11',
               attr='高德-街道路网图',
               zoom_start=10,
              )
    

    图片

    常规图

    folium.Map([40.002694, 116.322373],
               tiles= 'https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7',
               attr='高德-常规图',
               zoom_start=15,
              )
    

    图片

    4.2. 智图GeoQ

    反正我觉得这个蛮好的,用起来简单

    多种风格地图,即拿即用

    彩色版

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}',
                   attr='彩色版',
                   zoom_start=15,
                  )
    m
    

    图片

    暖色版

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetWarm/MapServer/tile/{z}/{y}/{x}',
                   attr='暖色版',
                   zoom_start=15,
                  )
    m
    

    图片

    灰色版

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetGray/MapServer/tile/{z}/{y}/{x}',
                   attr='灰色版',
                   zoom_start=15,
                  )
    m
    

    图片

    蓝黑版

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}',
                   attr='蓝黑版',
                   zoom_start=15,
                  )
    m
    

    图片

    英文版

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunityENG/MapServer/tile/{z}/{y}/{x}',
                   attr='英文版',
                   zoom_start=15,
                  )
    m
    

    图片

    中国行政区划边界

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://thematic.geoq.cn/arcgis/rest/services/ThematicMaps/administrative_division_boundaryandlabel/MapServer/tile/{z}/{y}/{x}',
                   attr='中国行政区划边界',
                  )
    m
    

    图片

    水系专题

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://thematic.geoq.cn/arcgis/rest/services/ThematicMaps/WorldHydroMap/MapServer/tile/{z}/{y}/{x}',
                   attr='水系专题',
                  )
    m
    

    图片

    街道网图

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://thematic.geoq.cn/arcgis/rest/services/StreetThematicMaps/Gray_OnlySymbol/MapServer/tile/{z}/{y}/{x}',
                   attr='街道网图',
                  )
    m
    

    图片

    暖色街道网图

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://thematic.geoq.cn/arcgis/rest/services/StreetThematicMaps/Warm_OnlySymbol/MapServer/tile/{z}/{y}/{x}',
                   attr='暖色-街道网图',
                  )
    m
    

    图片

    4.3. 腾讯地图

    tiles =  'https://rt0.map.gtimg.com/tile?z={z}&x={x}&y={-y}'
    folium.Map([39.904989, 116.405285],
               tiles= tiles,
               attr='腾讯地图'          
              )
    

    图片

    4.4. 天地图

    https://www.tianditu.gov.cn/

    需要注册一个key

    天地图影像

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://t7.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=',
                   attr='天地图-影像'
                  )
    m
    

    图片

    天地图影像注记

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://t7.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=',
                   attr='天地图-影像标注'
                  )
    m
    

    图片

    天地图矢量

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://t7.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=',
                   attr='天地图-矢量',
                   zoom_start=10,
                  )
    m
    

    图片

    天地图矢量注记

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://t7.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=',
                   attr='天地图-矢量注记'
                  )
    m
    

    图片

    天地图地形

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://t7.tianditu.gov.cn/ter_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ter&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=',
                   attr='天地图-地形',
                   zoom_start=3,
                  )
    m
    

    图片

    天地图地形注记

    m = folium.Map([40.002694, 116.322373],
                   tiles='http://t7.tianditu.gov.cn/cta_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cta&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=',
                   attr='天地图-地形标记',
                   zoom_start=3,
                  )
    m
    

    图片

    百度地图我这边测试失败了,暂时没有找到合适的替换方案。

    5. 补充

    其实,我们还可以找更多的地图底图瓦片URL来进行替换,多样化我们的地图绘制。

    另外,大家在用经纬度坐标点进行地图绘制的时候,比如标记点、绘制区域、热力图绘制等等,需要考虑经纬度坐标是哪个地图系下面的,然后再用对应地图系的相关底图进行绘制才准确!

    展开全文
  • 利利用用Python的的folium包包绘绘制制城城市市道道路路图图的的实实现现示示例例 这篇文章主要介绍了利用Python的folium包绘制城市道路图的实现示例文中通过示例代码介绍的非常详细对大 家的学习或者工作 有一定的...
  • folium进阶内容介绍

    千次阅读 2020-09-27 22:15:56
    ​ 上一篇中我们学习了folium的基础内容,从创建folium地图开始,通过主要参数修饰地图,尝试绘制Marker来标记特定地点等,实际上folium在地理信息可视化过程中重点在于绘制图像的高度可定制化。 二、处理GeoJSON和...
  • 有朋友可能没用过folium,它其实就是python的一个专业绘制地图的第三方库,所以在使用之前需要先安装它。 pip install folium 在安装完成之后,我们可以在jupyterlab进行演示如下: import folium m = folium.Map...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,737
精华内容 694
关键字:

folium

友情链接: 5.rar