Looking for a simple python library to create a choropleth map for your next web app or blog? Spent hours online looking for tutorials on how to get started? While there are a lot of popular libraries that can get you started with the simple implementation of static choropleth maps(matplotlib, seaborn etc), if Interactivity is what you are looking for, this is the article for you! While there are libraries like d3.js which can build custom maps, there are few simpler tools that you can explore. This blog talks about 3 such easy to implement but powerful opensource python libraries!
是否正在寻找一个简单的python库来为您的下一个Web应用程序或博客创建一个Choropleth映射? 在线花费了几个小时,寻找有关如何入门的教程? 虽然有很多流行的库可以让您开始使用简单的静态Choropleth贴图(matplotlib,seaborn等),但是如果您正在寻找Interactivity,那么这是为您准备的文章! 尽管有诸如d3.js之类的库可以构建自定义地图,但是您可以探索一些更简单的工具。 该博客讨论了3种如此易于实现但功能强大的开源python库!
Few months back , I wanted to create an interactive map for an interesting web app that we were developing. I spent hours online looking for the perfect library to get started with,but found it very difficult to run through the documentations, for there was no proper step by step guide for implementation and customizing the visuals as required. I wish I had a guide that compared the features and a proper implementation along with the details about customization.
几个月前,我想为我们正在开发的有趣的Web应用程序创建一个交互式地图。 我花了数小时在网上寻找一个理想的入门库,但是发现很难浏览所有文档,因为没有适当的逐步指南来实现所需的实现和自定义视觉效果。 我希望我能有一份指南,比较功能和适当的实现以及有关自定义的详细信息。
This is an attempt to create such a guide.The following write-up compares and contrasts the implementation of an interactive choropleth map along with the details and possible customizations to get the final output as required, using three of the popular map libraries available for Python —
这是尝试创建这样的指南的方法。下面的文章使用三个可用的Python流行地图库,将交互式Choropleth映射的实现与细节和可能的自定义进行比较和对比,以根据需要获得最终输出。 -
Altair —Simple and fast implementation with readily available set of features and pre-defined functionalities.
Altair-简单,快速的实施,具有随时可用的一组功能和预定义的功能。
Plotly — Variety of available implementations including Mapbox,Custom configurations and styling.
Plotly-各种可用的实现,包括Mapbox,自定义配置和样式。
Folium — Leaflet implementation with complete customization and interactivity including tool-tips, pop-ups and a lot more features.
Folium —具有完全自定义和交互性的传单实施,包括工具提示,弹出窗口和更多功能。
Choropleth maps require two kind of data in the background, one is the geospatial data — geographical boundaries to populate the tiles(generally Shape files or Geo JSONs)and two, data points against each tile in order to color code the map based on what that data represents.
Choropleth地图在后台需要两种数据,一种是地理空间数据-用于填充图块(通常为Shape文件或Geo JSON)的地理边界,而另一种是针对每个图块的数据点,以便根据该图为地图进行颜色编码数据代表。
Geo Pandas library is useful to get the data in the required format. This example uses a GeoJSON file of Indian states to populate data on top of India Map. You can get started with any publicly available shape file/GeoJSON.
Geo Pandas库对于获取所需格式的数据很有用。 本示例使用印度各州的GeoJSON文件在印度地图上填充数据。 您可以开始使用任何公开可用的形状文件/ GeoJSON。
Altair is a visualization library for Python based on Vega. It contains a simple implementation of choropleth maps with minimal code and good amount of interactivity like selections, tool-tips etc.
Altair是基于Vega的 Python可视化库。 它包含一个最小化代码的choropleth映射的简单实现,并且具有大量的交互性,例如选择,工具提示等。
Another good thing about this library is , it is compatible with fastpages. Simple and quick blogs can be made in minutes by converting a jupyter notebook with minimal amount of code. You can check out the github readme for the implementation.
这个库的另一个好处是,它与快速页面兼容。 通过使用最少的代码转换一个jupyter笔记本,可以在数分钟内创建简单快速的博客。 您可以查看实现的github 自述文件 。
Code snippet —
代码段-
# Importing required Librariesimport geopandas as gpdimport jsonimport altair as altimport pandas as pdReading the Shape file as a GeoPandas frame
读取Shape文件作为GeoPandas框架
gdf = gpd.read_file('states_india.shp')The dataframe looks like this
数据框如下所示
— Image by author —照片作者作者Creating base layer and choropleth layers
创建基础层和Choropleth层
# Creating configs for color,selection,hoveringmulti = alt.selection_multi(fields=['count','state'], bind='legend')color = alt.condition(multi, alt.Color('count', type='ordinal', scale=alt.Scale(scheme='yellowgreenblue')), alt.value('lightgray'))hover = alt.selection(type='single', on='mouseover', nearest=True, fields=['x', 'y'])#Creating an altair map layerchoro = alt.Chart(gdf).mark_geoshape( stroke='black').encode( color=color, tooltip=['state','count']).add_selection( multi ).properties( width=650, height=800)# Legendc1 = alt.layer(choro).configure_legend( orient = 'bottom-right', direction = 'horizontal', padding = 10, rowPadding = 15)#Adding Labelslabels = alt.Chart(gdf).mark_text().encode( longitude='x', latitude='y', text='count', size=alt.value(8), opacity=alt.value(0.6))c2 = alt.Chart(gdf).mark_geoshape( stroke='black').encode( color=color, tooltip=['state','count']).add_selection( hover ).project( scale=100, )(c1+labels).configure_view(strokeWidth=0)The above code should render an interactive choropleth map with hover tooltip display functionality and highlight on select(Click).
上面的代码应呈现具有悬停工具提示显示功能的交互式Choropleth贴图,并在select(Click)上突出显示。
Pros —
优点-
Simple and fast to implement. Pre-defined set of features for quick usage 实施简单快捷。 预定义的功能集,可快速使用 Compatibility with fastpages 与快速页面的兼容性Cons —
缺点 -
Less customization options and limited interactivity 更少的自定义选项和有限的交互性 No options to use external stylized tiles such as OSM,Mapbox etc. 没有使用外部风格化磁贴的选项,例如OSM,Mapbox等。 Limited documentation to use all the features that the API offers. 使用该API提供的所有功能的有限文档。Plotly’s Python graphing library makes interactive, publication-quality maps with a lot of interactivity and configurable features.
Plotly的 Python图形库制作具有许多交互性和可配置功能的交互式,具有出版质量的地图。
Availability of custom basemap configurations from Mapbox,OSM and other styling options along with simple implementation using plotly express and extensive documentation makes it one of the preferable options when it comes to creating interactive maps.
来自Mapbox,OSM和其他样式选项的自定义底图配置的可用性,以及使用绘图表达和大量文档的简单实现,使其成为创建交互式地图时的首选选项之一。
Code Snippet —
代码段-
# Importing required librariesfrom plotly.graph_objs import Scatter, Figure, Layoutimport plotlyimport plotly.graph_objs as goimport jsonimport numpy as npimport geopandas as gpdImporting Shape File
导入形状文件
gdf = gpd.read_file('states_india.shp')with open('states_india_1.json') as response: india = json.load(response)Creating base figure and adding tiles
创建基础图并添加图块
fig = go.Figure(go.Choroplethmapbox(geojson=india, locations=gdf['st_nm'], z=gdf['state_code'],featureidkey="properties.st_nm",colorscale="Viridis", zmin=0, zmax=25,marker_opacity=0.5, marker_line_width=1))fig.update_layout(mapbox_style="carto-positron", mapbox_zoom=3.5,mapbox_center = {"lat":23.537876 , "lon": 78.292142} ) fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})fig.show()The above code should render an interactive choropleth map with hover tooltip display and zoom functionality.
上面的代码应呈现具有悬停工具提示显示和缩放功能的交互式Choropleth贴图。
This plotly implementation comes with a lot of other features that can be explored here.
该绘图实现具有许多其他功能,可在此处进行探索。
Pros —
优点-
Very simple implementation with plotly express and graph libraries. Extensive documentation available. 使用plotly express和graph库非常简单的实现。 提供大量文档。 Lot of customization and configurable styling options. 许多自定义和可配置样式选项。 Compatible with dash and other options to embed the snippet on external web apps. 与破折号和其他选项兼容,以将代码段嵌入到外部Web应用程序中。Cons —
缺点-
No option to add popups and other interactive elements other than pre-defined options. 除预定义选项外,没有其他选项可添加弹出窗口和其他交互式元素。 Might require token access to work with few external styles. Limited options to control the zoom limits and related interactivity. 可能需要令牌访问才能使用很少的外部样式。 用于控制缩放限制和相关交互性的有限选项。Folium combines the ease of use of the Python ecosystem and the mapping strengths of the leaflet.js library.
Folium结合了Python生态系统的易用性和leaflet.js库的映射优势。
It enables us to render highly customizable,responsive and interactive choropleth maps as well as passing rich vector/raster/HTML visualizations as markers on the map.
它使我们能够渲染高度可定制的,响应式和交互式的十字形地图,并通过丰富的矢量/栅格/ HTML可视化效果作为地图上的标记。
The library has a number of built-in tilesets from OpenStreetMap, Mapbox, and Stamen, and supports custom tilesets with Mapbox or Cloudmade API keys. It supports both Image, Video, GeoJSON and TopoJSON overlays.
该库具有来自OpenStreetMap,Mapbox和Stamen的许多内置tileset,并支持具有Mapbox或Cloudmade API密钥的自定义tileset。 它同时支持Image,Video,GeoJSON和TopoJSON叠加层。
Code Snippet —
代码段-
# Importing required Librariesimport geopandas as gpdimport pandas as pdimport foliumimport brancaimport requestsimport jsonfrom folium.features import GeoJson, GeoJsonTooltip, GeoJsonPopupImporting Shape File
导入形状文件
gdf = gpd.read_file('states_india.shp')with open('states_india_1.json') as response: india = json.load(response)#Creating a custom tile (optional)import branca# Create a white image of 4 pixels, and embed it in a url.white_tile = branca.utilities.image_to_url([[1, 1], [1, 1]])Adding base layers and choropleth layers
添加基础层和Choropleth层
#Base layerf = folium.Figure(width=680, height=750)m = folium.Map([23.53, 78.3], maxZoom=6,minZoom=4.8,zoom_control=True,zoom_start=5, scrollWheelZoom=True,maxBounds=[[40, 68],[6, 97]],tiles=white_tile,attr='white tile', dragging=True).add_to(f)#Add layers for Popup and Tooltipspopup = GeoJsonPopup( fields=['st_nm','cartodb_id'], aliases=['State',"Data points"], localize=True, labels=True, style="background-color: yellow;",)tooltip = GeoJsonTooltip( fields=['st_nm','cartodb_id'], aliases=['State',"Data points"], localize=True, sticky=False, labels=True, style=""" background-color: #F0EFEF; border: 1px solid black; border-radius: 3px; box-shadow: 3px; """, max_width=800,)# Add choropleth layerg = folium.Choropleth( geo_data=india, data=gdf, columns=['st_nm', 'cartodb_id'], key_on='properties.st_nm', fill_color='YlGn', fill_opacity=0.7, line_opacity=0.4, legend_name='Data Points', highlight=True,).add_to(m)folium.GeoJson( india, style_function=lambda feature: { 'fillColor': '#ffff00', 'color': 'black', 'weight': 0.2, 'dashArray': '5, 5' }, tooltip=tooltip, popup=popup).add_to(g)fThe above code should render an interactive choropleth map with hover tooltip display ,click to zoom functionality and custom Popup display on click.
上面的代码应呈现具有悬停工具提示显示,单击以缩放功能和单击时自定义弹出窗口显示的交互式Choropleth贴图。
Pros —
优点-
Number of customization and configurable styling options along with unique interactive features like custom popups, click to zoom and custom tiling & backgrounds. 大量的自定义和可配置样式选项,以及独特的交互式功能,例如自定义弹出窗口,单击以缩放以及自定义平铺和背景。 Option to pass vector/raster/HTML visualizations as markers on the map. 选择传递矢量/栅格/ HTML可视化作为地图上的标记。 Option to render the map as html and other options to embed the snippet on external web apps. 提供将地图呈现为html的选项,以及将摘录嵌入外部Web应用程序的其他选项。 Decent amount of documentation available to explore all the available features. 大量的可用文档来探索所有可用功能。Cons —
缺点-
Slight learning curve to be able to leverage the features available. Also has some dependencies on few libraries that come with Folium. 轻微的学习曲线即可利用可用功能。 也依赖于Folium随附的几个库。When it comes to the interactivity with maps, these three tools enable us to implement tailor-made maps in our websites without much hassle.
关于与地图的交互性,这三个工具使我们能够轻松地在我们的网站中实施量身定制的地图。
This tutorial tries to be a guide in implementing a simple choropleth map with required interactivity ,taking a simple use-case. However, there are a lot of other features that can be explored by going through the documentation of the respective libraries. Hope this blog gives a basic understanding of the implementations that are possible. Please feel free to give your feedback , so that this blog can be updated/improved. You can reach out to me here for queries if any.
本教程以一个简单的用例,尝试作为实现具有所需交互性的简单Choropleth映射的指南。 但是,可以通过阅读各个库的文档来探索许多其他功能。 希望此博客对可能的实现有一个基本的了解。 请随时提供您的反馈,以便可以更新/改进此博客。 您可以在这里与我联系以查询任何问题。
Srihari Pramod
斯里哈里·普拉莫德
Data Analytics & Decision Science professional working on AI products and architectural technologies .Hyderabad,India.
致力于AI产品和建筑技术的数据分析和决策科学专业人员。印度海得拉巴。
翻译自: https://towardsdatascience.com/interactive-choropleth-maps-in-python-dd943b99df50
相关资源:Covid19-Choropleth-Map:covid19病例图-源码