百科问答小站 logo
百科问答小站 font logo



Python 如何画出漂亮的地图? 第1页

  

user avatar   nangao 网友的相关建议: 
      

推荐一个超好用的python包folium, 专门用于地理数据可视化,官方英文教程教程点击这里,查看本文源代码请点击这里(想要Python编程资料的童鞋请直接拉至最底部)。

使用方法很简单,操作如下:

  1. 导入包,创建一副世界地图
       import folium import pandas as pd  # define the world map world_map = folium.Map()  # display world map world_map     

2. 输入经纬度,尺度,在这里我们以旧金山(37.7749° N, 122.4194° W)为例。

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

更改地图显示,默认为'OpenStreetMap'风格,我们还可以选择'Stamen Terrain', 'Stamen Toner'等。

       # Create map and display it san_map = folium.Map(location=[latitude, longitude], zoom_start=12,tiles='Stamen Toner')     

3. 读取数据集(旧金山犯罪数据集)

       # Read Dataset  cdata = pd.read_csv('https://cocl.us/sanfran_crime_dataset') cdata.head()     

4. 在地图上显示前200条犯罪数据

       # get the first 200 crimes in the cdata limit = 200 data = cdata.iloc[0:limit, :]  # Instantiate a feature group for the incidents in the dataframe incidents = folium.map.FeatureGroup()  # Loop through the 200 crimes and add each to the incidents feature group for lat, lng, in zip(cdata.Y, data.X):     incidents.add_child(         folium.CircleMarker(             [lat, lng],             radius=7, # define how big you want the circle markers to be             color='yellow',             fill=True,             fill_color='red',             fill_opacity=0.4         )     )  # Add incidents to map san_map = folium.Map(location=[latitude, longitude], zoom_start=12) san_map.add_child(incidents)     

5. 添加地理标签

       # add pop-up text to each marker on the map latitudes = list(data.Y) longitudes = list(data.X) labels = list(data.Category)  for lat, lng, label in zip(latitudes, longitudes, labels):     folium.Marker([lat, lng], popup=label).add_to(san_map)          # add incidents to map san_map.add_child(incidents)     

6. 统计区域犯罪总数

       from folium import plugins  # let's start again with a clean copy of the map of San Francisco san_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(san_map)  # loop through the dataframe and add each data point to the mark cluster for lat, lng, label, in zip(data.Y, data.X, cdata.Category):     folium.Marker(         location=[lat, lng],         icon=None,         popup=label,     ).add_to(incidents)  # add incidents to map san_map.add_child(incidents)     

7. 读取geojson文件,可视化旧金山市10个不同Neighborhood的边界

       import json import requests  url = 'https://cocl.us/sanfran_geojson' san_geo = f'{url}' san_map = folium.Map(location=[37.77, -122.4], zoom_start=12) folium.GeoJson(     san_geo,     style_function=lambda feature: {         'fillColor': '#ffff00',         'color': 'black',         'weight': 2,         'dashArray': '5, 5'     } ).add_to(san_map)  #display map san_map     

8. 统计每个区域的犯罪事件数目

       # Count crime numbers in each neighborhood disdata = pd.DataFrame(cdata['PdDistrict'].value_counts()) disdata.reset_index(inplace=True) disdata.rename(columns={'index':'Neighborhood','PdDistrict':'Count'},inplace=True) disdata     

9. 创建Choropleth Map (颜色深浅代表各区犯罪事件数目)

       m = folium.Map(location=[37.77, -122.4], zoom_start=12) folium.Choropleth(     geo_data=san_geo,     data=disdata,     columns=['Neighborhood','Count'],     key_on='feature.properties.DISTRICT',     #fill_color='red',     fill_color='YlOrRd',     fill_opacity=0.7,     line_opacity=0.2,     highlight=True,     legend_name='Crime Counts in San Francisco' ).add_to(m) m     

10. 创建热力图

       from folium.plugins import HeatMap  # let's start again with a clean copy of the map of San Francisco san_map = folium.Map(location = [latitude, longitude], zoom_start = 12)  # Convert data format heatdata = data[['Y','X']].values.tolist()  # add incidents to map HeatMap(heatdata).add_to(san_map)  san_map     

本文源代码Jupyter notebook地址:

GitHub下载地址:

最后,folium还可以用来创建动态热力图,动态路径图等,具体可参考Medium上的这篇文章。

实现效果如下图所示 (直接从Medium上抱过来的图,详细代码请点击上述链接)。

----------------

最近好多小伙伴私信我推荐一些学习编程的经验,我给大家几点建议:

1. 尽量不去看那些冗长的视频教程,不是说学不到知识,而是,在你学到知识之前,你可能已经睡着了 =_=

2. 不要贪多,选一个知名度高的python教程,教学为辅,练习为主。每天用15分钟学习课程,剩余时间就用来做编程练习好了。要随时记住,我们学习python的目的在于会用,而不是背过了多少知识点。

嘻嘻,我想给大家推荐一款我超喜欢的python课程——夜曲编程。我闲没事在上面刷了一些编程题目,竟然回想起,当年备考雅思时被百词斩支配的恐惧。还别说,这款课程真是百词斩旗下的。哈哈,一股熟悉的亲切感扑面而来。

言归正传,这款课程对新手小白超级适合。虽然有手机app,但我建议你们用网页端学习(如果你是在地铁上用手机码代码的神仙,当我没说)。最关键的是,它是免费的!关注同名公众号可以直接领取(你懂的)

最后,我的终极建议是:无论选什么教程,贪多嚼不烂,好好专注一门课程,勤加练习才是提高编程水平的王道。等基础知识学的差不多了,去Kaggle上参加几场比赛,琢磨琢磨别人的编程思路和方法就完美啦!

我的其他回答

哪些 Python 库让你相见恨晚?

学习python中的pandas有没有好的教程推荐?

机器学习中的因果关系: 从辛普森悖论(常见的统计学谬误)谈起

欢迎大家关注我的机器学习笔记专栏,我将用小白也能听懂的语言,为大家讲述机器学习中那些有趣好玩的知识 (●'◡'●)


user avatar   mo-cun-34-45 网友的相关建议: 
      

简单梳理几个Python优质地图可视化工具,有的擅长交互、有的擅长学术研究、有的擅长商用地图展示,每一个都很666,记得文末点赞❤️❤️


Echarts/pyecharts

pyecharts擅长商业交互可视化,地图是其重要一部分,有大量demo,代码拿来即可用。快速入门 :快速上手pyecharts 三维动态世界地图

世界航线图

bus路径图

中国地图

可视化大屏

纽约街道数据

深入学习:github.com/pyecharts/py

Kepler.gl

kepler.glUber开源的用于大规模地理空间数据集的可视化探索工具,可在Jupyter Notebook中使用,这里仅仅展示一些demo,

深入学习:github.com/keplergl/kep


Basemap

Basemap为地理空间数据可视化利器,偏学院派。举个栗子,我们生活的蓝色星球全貌,

       import pyproj import geos from mpl_toolkits.basemap import Basemap # Basemap依赖pyproj和geos,三者一起导入,不然报错 import matplotlib.pyplot as plt  plt.figure(dpi=150,figsize=(6,6))  m = Basemap(     projection='ortho',  #指定投影方式ortho     lat_0=0,     lon_0=140,  #设置投影中心     resolution=None  #设置分辨率 ) m.bluemarble(scale=0.5) #设置蓝色弹珠 (The Blue Marble)背景  plt.show();      
更多栗子,

深入学习:matplotlib.org/basemap/


Folium

Folium是Python数据处理优势和JavaScript地图库Leaflet.js地图可视化优势的完美结合,二者结合后即可绘制优美的交互式地图。
一些栗子~

       import folium  whm = folium.Map(     location=[30.5538, 114.31589],  #武昌区经纬度     zoom_start=10,  # 默认放大倍数 )  folium.Marker(  #添加位置标示     location=[30.5538, 114.31589],     popup="❤️武汉",     icon=folium.Icon(color="#ba2f2a", icon="info-sign"), ).add_to(whm)  folium.CircleMarker(  #圈地     location=[30.5538, 114.31589],     radius=100,  #圈半径     color="#c72e29",     fill=True,     fill_color="#c72e29", ).add_to(whm)  folium.Marker(      location=[30.34653, 114.27001],     popup="❤️",     icon=folium.Icon(color="blue", icon="info-sign"), ).add_to(whm)  folium.CircleMarker(       location=[30.34653, 114.31001],     radius=100,      color="#01a2d9",     fill=True,     fill_color="#01a2d9", ).add_to(whm) whm      

再举个栗子,
Heatmap

       # Heatmap import numpy as np import folium from folium.plugins import HeatMap  data = (np.random.normal(size=(50, 3)) * np.array([[1, 1, 1]]) +         np.array([[39.904989, 116.4052859, 1]])).tolist()  m = folium.Map([39.904989, 116.4052859], zoom_start=6) HeatMap(data, radius=20).add_to(m) m      


Minicharts

Marker

ImageOverlay

choropleth

Heatmap with time

MiniMap

除此之外,Folium还有很多的插件

深入学习:python-visualization.github.io


ipyleaflet

ipyleafletJupyter Notebook的一个扩展擅长交互式地图
安装

       pip install ipyleaflet jupyter nbextension enable --py --sys-prefix ipyleaflet      

举个栗子,

       from ipyleaflet import Map, MagnifyingGlass, basemaps, basemap_to_tiles  m = Map(center=(30.5538, 114.31589), zoom=1.5)  topo_layer = basemap_to_tiles(basemaps.OpenTopoMap) magnifying_glass = MagnifyingGlass(layers=[topo_layer])  m.add_layer(magnifying_glass)  m      


更多栗子,

进一步学习:github.com/jupyter-widg


Cartopy

Cartopy为Basemap的继承者。
安装

       brew install proj geos #安装依赖 pip install cartopy -i https://pypi.tuna.tsinghua.edu.cn/simple #清华源光速安装      

举个栗子,
路线图

       import cartopy import matplotlib.pyplot as plt  plt.figure(dpi=150) plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']  ax = plt.axes(projection=ccrs.PlateCarree())  #默认投影PlateCarree ax.stock_img()  x_lon, x_lat = -55, -10, wh_lon, wh_lat = 114.30943, 30.59982  plt.plot(     [x_lon, wh_lon],     [x_lat, wh_lat],     color='#dc2624',     linewidth=1,     marker='o',     transform=ccrs.Geodetic(), )  plt.plot(     [x_lon, wh_lon],     [x_lat, wh_lat],     color='#01a2d9',     linestyle='--',     transform=ccrs.PlateCarree(), )  plt.text(x_lon - 3,          x_lat - 12,          'xx市',          horizontalalignment='right',          transform=ccrs.Geodetic())  plt.text(wh_lon + 3,          wh_lat - 12,          '武汉',          horizontalalignment='left',          transform=ccrs.Geodetic())      


更多栗子,

交互图

风杆图

深入学习:scitools.org.uk/cartopy


geopandas

geopandas依赖pandas、fiona及matplotlib「GeoPandas是Pandas在地理数据处理方向的扩展,使用shapely地理数据分析、fiona执行地理数据读取、matplotlib执行绘图」。举几个栗子~

       import matplotlib.pyplot as plt import geopandas  #读入数据 world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) cities = geopandas.read_file(     geopandas.datasets.get_path('naturalearth_cities'))  #画图 fig, ax = plt.subplots(2, 1, dpi=200) world.plot(column='pop_est', cmap='Set1_r', ax=ax[0]) world.plot(column='gdp_md_est', cmap='Set1', ax=ax[1]) plt.show()      


更多例子,如Plotting with CartoPy

Choro legends

kdeplot

进一步学习:github.com/geopandas/ge


geoplot

geoplot是一个high-level的Python地理数据可视化工具,是cartopymatplotlib的扩展,geoplot 之于cartopy,犹如seaborn之于matplotlib.直接看demo:桑基图 (Sankey)

添加散点

添加核密度估计图

分级统计图

深入学习:github.com/ResidentMari


Plotly/plotly-express

专业的交互式可视化工具,在Python、R、JavaScript方向都有API,

快速入门:❤️快速上手plotly-express❤️
subplots

scatter

Marker/Line

choropleth

Density Heatmap

facets

深入学习:plotly.com/python/


欢迎关注❤️❤️:pythonic生物人




  

相关话题

  如何在 Excel 上做数据地图? 
  目前强化学习在控制领域的应用有哪些? 
  如何系统地自学 Python? 
  Excel 的 VBA 现在还算是办公利器吗? 
  什么是无监督学习? 
  如何评价李飞飞和李佳加盟谷歌? 
  中国带有东西南北的行政区名是怎么来的? 
  东南亚国家形状为什么一头大一头小? 
  如何评价 MXNet 被 Amazon AWS 选为官方深度学习平台? 
  神经网络中如果一个重要特征C等于特征A+特征B(算数意义上的相加),选特征的时候还有必要选特征C吗? 

前一个讨论
世界上有哪些代码量很少,但很牛逼很经典的算法或项目案例?
下一个讨论
如果人能获得自己的 root 权限,会怎样?





© 2024-05-17 - tinynew.org. All Rights Reserved.
© 2024-05-17 - tinynew.org. 保留所有权利