CWhite
CWhite

Reputation: 11

Python: How to use matplotlib basemap with shapefiles

for a project at my university I want to use Python 2.7 to show a map of a (German) city, mostly the roads, and in the end including the geo-location of several service points. I have basic knowledge of Python, and I feel that I do not get access to the steps I need to do in order to reach my goal.

I used basemap to restrict the area with lon and lat where the city is. Then I wanted to use a shapefile to include roads that have been provided, but I got the error message "RuntimeError: Can not put single artist in more than one figure". Despite searching I couldn't find a solution. Here is the code I used:

import matplotlib.pyplot as plt
import matplotlib.cm
import numpy as np
import shapefile as shp

from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from matplotlib.collections import LineCollection
from matplotlib.collections import PolyCollection
from matplotlib.colors import Normalize

fig, ax=plt.subplots(figsize=(10,20))

m = Basemap(resolution='c', # c, l, i, h, f or None
            projection='merc',
           #lat lowleft: llcrnrlon, lon low right llcrnrlat
            #lat upleft urcrnrlon=47.81,, lon up right urcrnrlat=10.5
            llcrnrlon=8.45195, llcrnrlat=49.477816, urcrnrlon=8.491432, urcrnrlat=49.50117)    

drawmapboundary(fill_color='aqua')
m.fillcontinents(color='firebrick')
m.drawrivers(color='aqua')
m.drawcoastlines()

plt.show()

m.readshapefile('roads', 'roads')

Then I got me the Google Maps APIs, but it seems to me that I can't use them for giving out a map. Also, loading the pygmaps wrapper crashes: "ImportError: No module named pygmaps", and anyway, I wouldn't know how to use it.

Does someone here know which steps I could take to fulfill my goal? I would be really very grateful for advice. Thanks in advance!

Upvotes: 0

Views: 2257

Answers (1)

Brandon Molyneaux
Brandon Molyneaux

Reputation: 1763

Using the docs, reading in a shapefile is as simple as:

m.readshapefile('path_to/shapefile/shapefile', 'name')

Do note that the first argument doesn't require a .shp at the end of the shapefile name. If you want to access the elements of the shapefile:

name_info = m.readshapefile('path_to/shapefile/shapefile', 'name')
for info, shape in zip(m.name_info, m.name):
    print(info)

This will print out dictionaries with your attributes and values within that shapefile. From there, you can play around with the shapefile.

Upvotes: 1

Related Questions