Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

matplotlib - How to draw rectangles on a Basemap

I'm looking for a way to plot filled rectangles on a Basemap. I could easily draw the rectangle's edges using the drawgreatcircle method, but I cannot find a way to actually fill these rectangles (specifying color and alpha).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can add a matplotlib.patches.Polygon() directly to your axes. The question is whether you want your rectangles defined the plot coordinates (straight lines on the plot) or in map coordinates (great circles on the plot). Either way, you specify vertices in map coordinates and then transform them to plot coordinates by calling the Basemap instance (m() in the below example), build a Polygon yourself, and add it manually to the axes to be rendered.

For rectangles defined in plot coordinates, here's an example:

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

def draw_screen_poly( lats, lons, m):
    x, y = m( lons, lats )
    xy = zip(x,y)
    poly = Polygon( xy, facecolor='red', alpha=0.4 )
    plt.gca().add_patch(poly)

lats = [ -30, 30, 30, -30 ]
lons = [ -50, -50, 50, 50 ]

m = Basemap(projection='sinu',lon_0=0)
m.drawcoastlines()
m.drawmapboundary()
draw_screen_poly( lats, lons, m )

plt.show()

For rectangles defined in map coordinates, use the same approach, but interpolate your line in map space before transforming to plot coordinates. For each line segment, you'll have to do:

lats = np.linspace( lat0, lat1, resolution )
lons = np.linspace( lon0, lon1, resolution )

Then transform these map coordinates to plot coordinates (as above, with m()) and again create a Polygon with the plot coordinates.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...