I want to use imshow (for example) to display some data inside the borders of the country (as an example, I chose the USA). The simple example below illustrates what I want:
import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import RegularPolygon data = np.arange(100).reshape(10, 10) fig = plt.figure() ax = fig.add_subplot(111) im = ax.imshow(data) poly = RegularPolygon([ 0.5, 0.5], 6, 0.4, fc='none', ec='k', transform=ax.transAxes) im.set_clip_path(poly) ax.add_patch(poly) ax.axis('off') plt.show()
Result:

Now I want to do this, but instead of a simple polygon, I want to use a complex US shape. I have created some examples of data contained in the "Z" array, as can be seen from the code below. It is these data that I want to display using the colourmap, but only within the borders of the continental United States.
So far I have tried the following. I get the form file from here , contained in the file "nationp010g.shp.tar.gz", and I use the Basemap module in python to build the USA. Please note that this is the only method I found that gives me the opportunity to get the polygon area I need. If there are alternative methods, I would be interested in them too. Then I create a polygon called "mainpoly", which is almost a polygon that I want to color blue:

Please note that only one body is colored, all other disjoint polygons remain white:

So, the blue colored area is almost what I want, note that there are undesirable borders around Canada because the border actually passes through some lakes, but this is a small problem. The real problem is why my imshow data is not displayed in the USA? Comparing my first and second code examples, I donβt understand why I do not get the clipped imshow in my second example, as I do in the first. Any help would be appreciated in understanding what I am missing.
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap as Basemap from matplotlib.patches import Polygon
Update
I understand that the line
ax.add_patch(mainpoly)
doesn't even add a polygon shape to the plot. I do not use it correctly? As far as I know, mainpoly was correctly calculated using the Polygon () method. I checked that the coordinate inputs are reasonable:
plt.plot(mainseg[:,0], mainseg[:,1] ,'.')
which gives
