我在绘图时遇到困难,例如跨越使用 matplotlib-basemap 生成的 map 边界的多边形。在下面的示例中, map 边界由日期变更线指定。我尝试通过指定三角形顶点的坐标来绘制跨越日期变更线的三角形。当所有坐标都在 map 内时,这工作正常,但如果它们跨越 map 边界, basemap 会执行奇怪的外推,因为它似乎不知道如何以正确的方式绘制矩形。
在我看来,正确的方法意味着绘制三角形直到 map 边界,然后在 map 的另一侧继续。
下面是最小代码示例和说明一般问题的图。 非常欢迎任何如何以通用方式解决此问题的想法。
from mpl_toolkits.basemap import Basemap
import matplotlib.pylab as plt
import numpy as np
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib as mpl
from matplotlib.collections import PatchCollection
![plt.close('all')
Path = mpath.Path
fig=plt.figure(); ax=fig.add_subplot(121); ax1=fig.add_subplot(122)
def do_plot(ax,lons,lats,title):
patches=\[\]
m = Basemap(projection='robin', resolution='c',lon_0=0.,ax=ax) #todo: how to make it properly work for other projections ???
m.drawmapboundary(fill_color='grey')
m.drawcoastlines()
#--- generate first sample with no problem
x,y=m(lons,lats)
verts = np.asarray(\[x,y\]).T
codes = \[Path.MOVETO,Path.LINETO,Path.LINETO\]
patches.append(mpatches.PathPatch(mpath.Path(verts, codes,closed=True)))
#--- generate collection
cmap = plt.cm.get_cmap('jet', 50); norm = mpl.colors.Normalize(vmin=None, vmax=None) #colorbar mapping
collection = PatchCollection(patches, cmap=cmap,norm=norm, alpha=1.,match_original=False) #construct library of all objects
colors = np.asarray(np.random.random(len(patches)))
collection.set_array(np.array(colors)) #assign data values here
#--- do actual plotting
im=m.ax.add_collection(collection)
ax.set_title(title)
do_plot(ax,\[-10.,0.,20.\],\[30.,50.,20.\],'This works')
do_plot(ax1,\[170,180,-175\],\[30.,50.,20.\],'... and here is the boundary problem')
plt.show()][1]
最佳答案
您无法通过简单的方式解决 basemap 的这个问题。在您的行 x,y=m(lons,lats)
中,您已将点转换为 map 坐标,并且绘制多边形只是在这些投影点之间绘制。
您可以尝试使用 Cartopy ,可以做到这一点。 This example可能有帮助。
关于python - 使用 matplotlib-basemap 在边界处绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17423692/