【问题标题】:Plotting geoJSON Tracks Across Dateline without Errant Lines with Cartopy使用 Cartopy 绘制跨越日期线的 geoJSON 轨迹而不会出现错误线
【发布时间】:2021-10-31 04:51:32
【问题描述】:

我正在制作一张世界地图,其中包含 geoJSON 中提供的船舶轨迹 - 当轨迹越过 180/-180 线时,我会在世界范围内得到一条错误的线。为了简化事情,我将 track.json 文件简化为单个轨道,但通常的文件有多个船舶轨道。

然后将绘图保存为分辨率为 4000x2000 像素的无边界世界地图 - 请参阅:

https://www.oceanic.udel.edu/globaldataview/rt_content/ships/latest/ship_locations.jpg

import os
import matplotlib as mpl
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import geopandas as gpd

def main():

    tracks = gpd.read_file('https://www.researchvessels.org/data/tracks.json')

    fig = plt.figure(dpi=100, figsize=(40, 20), frameon=False)
    plt.axis('off')
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
    ax.set_extent([-180, 180, -90, 90], ccrs.PlateCarree())
    ax.set_axis_off()
    tracks.plot(ax=ax, color="yellow")
    fig.add_axes(ax)
    # Background Image below is available via https://www.researchvessels.org/data/nasa_bm_default.jpg
    img = plt.imread('c:/scripts/NASA_BM_default.jpg')
    img_extent = (-180, 180, -90, 90)
    ax.imshow(img, origin='upper', extent=img_extent, transform=ccrs.PlateCarree(), aspect='auto')
    fig.subplots_adjust(bottom = 0)
    fig.subplots_adjust(top = 1)
    fig.subplots_adjust(right = 1)
    fig.subplots_adjust(left = 0)
    plt.show()
    plt.close(fig)

【问题讨论】:

    标签: python-3.x geojson geopandas cartopy


    【解决方案1】:

    要正确绘制轨迹,您需要清理跨越日期线的轨迹中longitude 的值。

    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs
    import geopandas as gpd
    
    def sanitize_lonlist(lons):
        new_list = []
        oldval = 0
        # used to compare with the adjacent longitudes
        # and values exceed, disconnect linestring
        treshold = 10   
        for ix,ea in enumerate(lons):
            diff = oldval - ea
            if (ix>0):
                if (diff>treshold):
                    ea = ea+360
            oldval = ea
            new_list.append(ea)
        return new_list
    
    tracks = gpd.read_file('https://www.researchvessels.org/data/tracks.json')
    # grab x and y of the first geometry object
    xs = tracks.geometry[0].xy[0]
    ys = tracks.geometry[0].xy[1]
    
    ax = plt.axes(projection=ccrs.PlateCarree()) 
    ax.set_global() 
    ax.coastlines()
    
    # plot the geometry using sanitized values
    ax.plot(sanitize_lonlist(xs), ys, transform=ccrs.PlateCarree(), color='red', lw=3)
    plt.show()
    

    输出:

    【讨论】:

      猜你喜欢
      • 2021-08-16
      • 1970-01-01
      • 2015-02-22
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      相关资源
      最近更新 更多