[Introduction to python geographic information drawing] cartopy learning

Introduction to cartopy

  • cartopy is a Python library for drawing map projections and visualizing geographic data.
  • It is built on the basis of matplotlib and is specially used for making maps and charts of geographic data.
  • cartopy aims to make map making easier and more intuitive, while providing some powerful functions for working with geographic data and projections.

Cartopy draws administrative maps of China (cartopy version is 0.20.0)

  • Provincial boundary display
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader

fig = plt.figure(figsize=(12,8))
# 投影方式
crs = ccrs.PlateCarree()
ax = fig.add_subplot(111, projection=crs)
# 显示范围
extents = [70, 140, 0, 55]
ax.set_extent(extents, crs)

filepath = '.\bou2_4p.shp'
file_nineline = ".\九段线.shp"
reader = shpreader.Reader(filepath)
reader_nineline = shpreader.Reader(file_nineline)
geoms = reader.geometries()
geoms_nineline = reader_nineline.geometries()
# 绘制陆地和九段线
ax.add_geometries(geoms, crs, lw=0.5, fc='none')
ax.add_geometries(geoms_nineline, crs, lw=0.5, fc='none')
reader.close()
reader_nineline.close()
plt.show()

insert image description here

  • Municipal administrative unit display
# 在以上代码中添加市图层即可
city_files = shpreader.Reader(r'.\市.shp')
ax.add_geometries(city_files.geometries(), crs, lw=0.5, fc='none')
reader.close()

insert image description here

  • County-level administrative unit display
# 在以上代码中添加市图层即可
county_files = shpreader.Reader(r'.\县.shp')
ax.add_geometries(county_file.geometries(), crs, lw=0.5, fc='none')
reader.close()

insert image description here

Cartopy draws the administrative map of China, and a single province is subdivided to draw the urban area

  • Sometimes we only pay attention to the subdivided urban areas in a province, but not other provinces, then we need to draw the city boundaries in a single province
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader

extents = [70, 140, 0, 55]
crs = ccrs.PlateCarree()
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111, projection=crs)
ax.set_extent(extents, crs)

city_reader = shpreader.Reader(r'.\市.shp')
reader = shpreader.Reader('.\bou2_4p.shp')
reader_nineline = shpreader.Reader(".\九段线.shp")
geoms = reader.geometries()
geoms_nineline = reader_nineline.geometries()

# 河南省市区
for record, geos in zip(city_reader.records(),city_reader.geometries()):
    if record.attributes['省'] == '河南省':
        ax.add_geometries([geos], crs, edgecolor='r', facecolor='none', lw=1)
records = city_reader.records()
# 中国地图
ax.add_geometries(geoms, crs, lw=0.5, fc='none')
ax.add_geometries(geoms_nineline, crs, lw=0.5, fc='none')

reader.close()
reader_nineline.close()
city_reader.close()

plt.show()

insert image description here

Some problems with the cartopy library

  • Cartopy relies on the shapefile library to read files, but only one parameter is set in the initialization, that is, the name of the file, and there is no setting of variable parameters . This makes the document encoding format not UTF-8 type files, garbled characters appear when reading, and keyword parameters cannot be used to filter data. as the picture shows:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
import shapefile
filepath = '.\bou2_4p.shp'
x = shpreader.Reader(filepath)
for i in x.records():
    print(i.attributes)

The shapefile reads the bou2_4p.shp file, and the NAME shows garbled characters in Chinese

  • In the shapefile source code, only the filename parameter is set , and there is no variable parameter setting, so the encoding parameter cannot be selected.
    insert image description here
  • Therefore, in the above drawing example, it is difficult to use keywords to change the boundary of "Henan Province". Therefore, check the source code and use the following method to modify it to complete the above function.
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
import shapefile
import shapely.geometry as sgeom

# 将shpreader中的geometries方法复制过来
def geometries(reader):
    for shape in reader.iterShapes():
        if shape.shapeType != shapefile.NULL:
            yield sgeom.shape(shape)


extents = [70, 140, 0, 55]
crs = ccrs.PlateCarree()
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111, projection=crs)
ax.set_extent(extents, crs)

filepath = '.\bou2_4p.shp'
file_nineline = ".\九段线.shp"
# 直接使用shapefile进行文件读取
reader = shapefile.Reader(filepath, encoding="gbk")
reader_nineline = shpreader.Reader(file_nineline)
geoms = geometries(reader)
geoms_nineline = reader_nineline.geometries()
ax.add_geometries(geoms, crs, lw=0.5, fc='none')
ax.add_geometries(geoms_nineline, crs, lw=0.5, fc='none')

city_reader = shpreader.Reader(r'.\市.shp')

for record, geos in zip(city_reader.records(),city_reader.geometries()):
    if record.attributes['省'] == '河南省':
        ax.add_geometries([geos], crs, edgecolor='#733b97', facecolor='none', lw=1)
records = city_reader.records()

for record, geos in zip(reader.records(), geometries(reader)):
    colors = {
    
    '河南省': "b", "河北省": "g", "山东省": 'r'}
    if record.as_dict()['NAME'] in ['河南省', "河北省", "山东省"]:
        ax.add_geometries([geos], crs, edgecolor=colors[record.as_dict()['NAME']], facecolor='none', lw=1)
records = city_reader.records()

reader.close()
city_reader.close()
reader_nineline.close()

plt.show()

insert image description here

  • Use keywords to view and filter data
for record, geos in zip(reader.records(), geometries(reader)):
    print(record)

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/qq_38734327/article/details/132357838