Question

I have difficulties in plotting e.g. polygons across the boundaries of a map generated using matplotlib-basemap. In the example below, the map boundary is specified by the dateline. I try to plot a triangle across the dateline by specifying the coordinates of vertices of a triangle. This works fine when all coordinates are within the map, but if they go across the map boundary, basemap performs strange extrapolation, as it seems not to know how to draw the rectangles in the right way.

Right way would mean in my sense that the triangle is drawn until the map boundary and would then continue at the other side of the map.

Below is a minimum code example and a figure illustrating the general problem. Any ideas how to solve this problem in a general way are highly welcome.

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]

plotting problem

Was it helpful?

Solution

You cannot get around this problem with Basemap in a simple way. In your line x,y=m(lons,lats) you have transformed the points to map coordinates, and drawing the polygon just draws between those projected points.

You might try using Cartopy, which can do this. This example may help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top