简体   繁体   中英

Basemap and Matplotlib - Improving Speed

I'm creating a tool for geospatial visualization of economic data using Matplotlib and Basemap .

However, right now, the only way I thought of that gives me enough flexibility is to create a new basemap every time I want to change the data.

Here are the relevant parts of the code I'm using:

class WorldMapCanvas(FigureCanvas):

def __init__(self,data,country_data):
    self.text_objects = {}
    self.figure = Figure()
    self.canvas = FigureCanvas(self.figure)
    self.axes = self.figure.add_subplot(111)
    self.data = data
    self.country_data = country_data
    #this draws the graph
    super(WorldMapCanvas, self).__init__(Figure())
    self.map = Basemap(projection='robin',lon_0=0,resolution='c', ax=self.axes)
    self.country_info = self.map.readshapefile(
        'shapefiles/world_country_admin_boundary_shapefile_with_fips_codes', 'world', drawbounds=True,linewidth=.3)

    self.map.drawmapboundary(fill_color = '#85A6D9')
    self.map.fillcontinents(color='white',lake_color='#85A6D9')
    self.map.drawcoastlines(color='#6D5F47', linewidth=.3)
    self.map.drawcountries(color='#6D5F47', linewidth=.3)
    self.countrynames = []
    for shapedict in self.map.world_info:
        self.countrynames.append(shapedict['CNTRY_NAME'])

    min_key = min(data, key=data.get)
    max_key = max(data, key=data.get)
    minv = data[min_key]
    maxv = data[max_key]

    for key in self.data.keys():
        self.ColorCountry(key,self.GetCountryColor(data[key],minv,maxv))
    self.canvas.draw()

How can I create these plots faster?

I couldn't think of a solution to avoid creating a map every time I run my code. I tried creating the canvas/figure outside of the class but it didn't make that much of a difference. The slowest call is the one that creates the Basemap and loads the shape data. Everything else runs quite fast.

Also, I tried saving the Basemap for future use but since I need new axes I couldn't get it to work. Maybe you can point me in the right direction on how to do this.

I'd like you to know that I'm using the canvas as a PySide QWidget and that I'm plotting different kinds of maps depending on the data, this is just one of them (another would be a map of Europe, for instance, or the US).

You can pickle and unpickle Basemap instances ( there is an example of doing this in the basemap source ) which might save you a fair chunk of time on the plot creation.

Additionally, it is probably worth seeing how long the shapefile reading is taking (you may want to pickle that too).

Finally, I would seriously consider investigating the option of updating country colours for data, rather than making a new figure each time.

HTH,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM