Suppose that we are importing the shapefiles from a source that changes the values fairly often. One of the shapefiles contains values between 1 and 5, but vary in the size and values (e.g. the first time the shapefile is grabbed from the source, it contains 1 value. The next time it's grabbed from the source, it contains 4 values) The other shapefile contains animal names, but there's only 3 possibilities, and just like the first shapefile, it can vary in how many values it has.
Let's say shapefile1 contains '2' and '3', while shapefile2 contains 'Horse' when we first grab the zip files. On the legend, I only want '2', '3' and 'Horse' to show with the correct icons (see script below). The next time we run the program and grab the zip folder, shapefile1 contains '1', '2', '4', '5', and shapefile2 contains 'Bird', 'Cat'. The legend should have '1', '2', '4', '5', 'Bird', 'Cat'.
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import requests, zipfile, io
def plot_stuff_sf1(x, y, color):
m.plot(x, y, c = color, mec = 'k', m = 'o', ms = 5., ls = None, mew = 1.)
def plot_stuff_sf2(x, y, marker):
m.plot(x, y, color = 'c', mec = 'k', m = marker, ms = 5., ls = None, mew = 1.)
#gets zipped file and stores on computer
zip_file_url = 'zippedfile/location'
r = requests.get(zip_file_url)
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall('/path/to/save/files')
m = Basemap(projection = 'merc', llcrnrlat= 90, urcrnrlat= -90,
llcrnrlon= -180, urcrnrlon= 180, lat_ts=40,resolution='i')
m.readshapefile('/path/to/shapefile', 'name')
points_info = m.readshapefile('/path/to/shapefile', 'name')
for info, shape in zip(m.name_info, m.name):
x, y = zip(shape)
if info['NUMBER'] == '1':
plot_stuff_sf1(x, y, 'c')
elif info['NUMBER'] == '2':
plot_stuff_sf1(x, y, 'm')
elif info['NUMBER'] == '3':
plot_stuff_sf1(x, y, 'g')
elif info['NUMBER'] == '4':
plot_stuff_sf1(x, y, 'r')
elif info['NUMBER'] == '5':
plot_stuff_sf1(x, y, 'k')
m.readshapefile('/path/to/shapefile2', 'name2')
name_info2 = m.readshapefile('/path/to/shapefile2', 'name2')
for info, shape in zip(m.name_info2, m.name2):
x, y = zip(shape)
if info['VALUE'] == 'Bird':
plot_stuff_sf2(x, y, 'o')
elif info['VALUE'] == 'Horse':
plot_stuff_sf2(x, y, 'D')
elif info['VALUE'] == 'Cat':
plot_stuff_sf2(x, y, '>')
I didn't include the legend code, as that's where I'm getting tripped up. I've looked at the documentation and tried plt.legend(handles = [...])
, but for some reason it didn't work (even when I copied/pasted the code from the documentation and integrated it with my script).