使用geopandas和matplotlib绘制地图

Her*_*c01 5 python geopandas

我有一个小型的csv,具有来自英国伯明翰的6个坐标。我用熊猫阅读了csv,然后将其转换为GeoPandas DataFrame,并使用Shapely Points更改了我的纬度和经度列。我现在正在尝试绘制我的GeoDataframe,我所能看到的就是要点。如何获得伯明翰地图?一个有关GeoPandas的良好文档来源也将受到高度赞赏。

from shapely.geometry import Point
import geopandas as gpd
import pandas as pd

df = pd.read_csv('SiteLocation.csv')
df['Coordinates'] = list(zip(df.LONG, df.LAT))
df['Coordinates'] = df['Coordinates'].apply(Point)
# Building the GeoDataframe 
geo_df = gpd.GeoDataFrame(df, geometry='Coordinates')
geo_df.plot()  
Run Code Online (Sandbox Code Playgroud)

kee*_*ive 8

GeoPandas文档包含一个有关如何向地图添加背景的示例(https://geopandas.readthedocs.io/en/latest/gallery/plotting_basemap_background.html),下面将对其进行详细说明。


您将不得不处理图块(即通过网络服务器提供的(png)图像),其网址应为

http://.../Z/X/Y.png,其中Z是缩放级别,X和Y标识图块

geopandas的文档显示了如何将图块设置为绘图的背景,如何获取正确的图块以及完成空间同步等所有其他困难的工作,等等。


安装

假设已经安装了GeoPandas,则还需要该contextily软件包。如果您在Windows下,则可能要看一下如何上下文安装?

用例

创建一个python脚本并定义上下文帮助函数

import contextily as ctx

def add_basemap(ax, zoom, url='http://tile.stamen.com/terrain/tileZ/tileX/tileY.png'):
    xmin, xmax, ymin, ymax = ax.axis()
    basemap, extent = ctx.bounds2img(xmin, ymin, xmax, ymax, zoom=zoom, url=url)
    ax.imshow(basemap, extent=extent, interpolation='bilinear')
    # restore original x/y limits
    ax.axis((xmin, xmax, ymin, ymax))
Run Code Online (Sandbox Code Playgroud)

import matplotlib.pyplot as plt
from shapely.geometry import Point
import geopandas as gpd
import pandas as pd

# Let's define our raw data, whose epsg is 4326
df = pd.DataFrame({
    'LAT'  :[-22.266415, -20.684157],
    'LONG' :[166.452764, 164.956089],
})
df['coords'] = list(zip(df.LONG, df.LAT))

# ... turn them into geodataframe, and convert our
# epsg into 3857, since web map tiles are typically
# provided as such.
geo_df = gpd.GeoDataFrame(
    df, crs  ={'init': 'epsg:4326'},
    geometry = df['coords'].apply(Point)
).to_crs(epsg=3857)

# ... and make the plot
ax = geo_df.plot(
    figsize= (5, 5),
    alpha  = 1
)
add_basemap(ax, zoom=10)
ax.set_axis_off()
plt.title('Kaledonia : From Hienghène to Nouméa')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


注意:您可以使用zoom和查找地图的高分辨率。例如:

在此处输入图片说明

...并且此类分辨率隐式要求更改x / y限制。