如何用底图绘制以太平洋为中心的形状文件?

2024-09-28 05:22:39 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Basemap的readshapefile进行打印时,如果定义的地图的中心位置不是shapefile的纵向中心,则只打印它的一部分。下面是一个使用Natural Earth's海岸线的示例:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

shpf = './NaturalEarth/ne_50m_land/ne_50m_land'

fig, ax = plt.subplots(nrows=1, ncols=1, dpi=100)

m = Basemap(
    ax = ax,
    projection = 'cyl',
    llcrnrlon = 0, llcrnrlat = -90,
    urcrnrlon = 360, urcrnrlat = 90
) 

m.readshapefile(shpf,'ne_50m_land')

m.drawmeridians(np.arange(0,360,45),labels=[True,False,False,True])

产生:

Image output

使用Basemap或Python有解决方法吗?我知道有些人在QGIS或类似的工具中重新定位shapefile,但每次创建新地图时都这样做似乎不实际,而且我的QGIS技能非常基本。在


Tags: importfalsetrueasnp地图pltax
1条回答
网友
1楼 · 发布于 2024-09-28 05:22:39

一种方法是告诉readshapefile不要直接绘制海岸线,然后在自己绘制之前操纵线段。下面是一个基于您的用例的示例:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

shpf = 'shapefiles/ne_50m_land'

fig, ax = plt.subplots(nrows=1, ncols=1, dpi=100)

m = Basemap(
    ax = ax,
    projection = 'cyl',
    llcrnrlon = 0, llcrnrlat = -90,
    urcrnrlon = 360, urcrnrlat = 90
) 

m.readshapefile(shpf,'ne_50m_land', drawbounds = False)

boundary = 0.0

for info, shape in zip(m.ne_50m_land_info, m.ne_50m_land):
    lons, lats = map(np.array, zip(*shape))

    sep = (lons <= boundary).astype(int)
    roots = np.where(sep[:-1]+sep[1:] == 1)[0]+1
    lower = np.concatenate([[0],roots]).astype(int)
    upper = np.concatenate([roots,[len(lons)]]).astype(int)

    for low, high in zip(lower,upper):
        lo_patch = lons[low:high]
        la_patch = lats[low:high]
        lo_patch[lo_patch<0] += 360
        x,y = m(lo_patch,la_patch)
        ax.plot(x,y,'k',lw=0.5)

m.drawmeridians(np.arange(0,360,45),labels=[True,False,False,True])

plt.show()

在上面的例子中,我按照Basemap documentation中解释的方式遍历形状文件的线段。首先,我认为只要在经度小于0的点上加360度就足够了,但是当海岸线穿过0度线时,就会得到水平线。因此,每当出现这样的交叉时,就必须将这些线切割成更小的线段。这很容易用numpy完成。然后我使用plot命令绘制海岸线。如果您想做更复杂的事情,请看一下Basemap documentation

最终结果如下:

result of the above code

希望这有帮助。

相关问题 更多 >

    热门问题