python 绘制中国地图并利用经纬度标注散点
所需要的包:GeoPandas,安装教程有很多,自行百度即可。
用到的中国地级市shp文件:链接:https://pan.baidu.com/s/18aaxczrz4tIRMeCusOrDQA
提取码:rav1
一、GeoPandas类简单介绍
GeoPandas实现了两个主要的数据结构,GeoSeries和GeoDataFrame。它们分别是pandas中Series和DataFrame的子类。实际上,如果你了解DataFrame结构,这个就很好理解了。
一个GeoSeries就是包含一个几何图形的序列,比如多边形、点。具体形式就在下图,如果想要绘图,很简单,只要用plot方法就可以,多边形GeoSeries绘制出来的就是多边图形, 点GeoSeries当然就是绘制点了。
多边形GeoSeries:
点GeoSeries:
绘图实例:
读取shp文件绘制中国地图
china_map=gp.GeoDataFrame.from_file("C:/Users/Administrator/Desktop/map_shp/shipnew
/中国行政区划2004_shp/dijishi_2004.shp",\
encoding = 'gb18030')
china_map.plot(figsize=(20,12),color="white", edgecolor="black")
利用经纬度绘制散点图:
lng = data2002com['lng']
lat= data2002com['lat']
pts = gp.GeoSeries([Point(x, y) for x, y in zip(lng, lat)])
pts.plot(figsize=(12,8))
二、世界地图标注实例
这一部分主要是解释官方网站的一个例子,为自己绘制地图标注散点做准备。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import os
import geopandas as gp
from shapely.geometry import Point
# 官方数据
world = gp.read_file(gp.datasets.get_path('naturalearth_lowres'))
cities = gp.read_file(gp.datasets.get_path('naturalearth_cities'))
#注意world.shape =(177,6)
# cities.shape = (202,2)
fig, ax = plt.subplots()
ax.set_aspect('equal')
world.plot(ax=ax, color='white', edgecolor='black')
cities.plot(ax=ax, marker='o', color='red', markersize=5)
plt.show()
绘图的机制其实很好理解,就是第一个图层是一个世界地图的多边形,第二个图层是一些城市的经纬度点,把这些经纬度点映射到世界地图上就是这个样了。
三、中国地图标注实例
只需要地图数据的shp文件,还有就是经纬度,就可以实现自己的地图。
china_map=gp.GeoDataFrame.from_file("C:/Users/Administrator/Desktop/map_shp/shipnew
/中国行政区划2004_shp/dijishi_2004.shp",\
encoding = 'gb18030')
data2002com = pd.read_excel(r'C:\Users\Administrator\Desktop\经纬度数据\按公司名称
\2002.xlsx')
# 几何图形
geo_ploy = china_map['geometry']
# 地图点
geo_point = gp.GeoSeries([Point(x, y) for x, y in zip(lng, lat)])
fig, ax = plt.subplots(figsize=(12,8))
ax.set_aspect('equal')
# 几何图形绘制
geo_ploy.plot(ax=ax, color='white', edgecolor='black')
# 地图点标注
geo_point.plot(ax=ax, marker='o', color='black', markersize=0.1)