Verzweifler
Verzweifler

Reputation: 940

Adding Colorbar legend to Basemap plot containing multiple shapefiles

I'm using Basemap to draw several shapefiles to one canvas, coloring with an index I calculated before. Now I'm trying to add a legend (colorbar) next to my image, but I can't get it to work. This is my code so far:

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

# Floats between 0 and 20
indexList = [*Previously calculated indices*]
minIndex = min(indexList)
maxIndex = max(indexList)

# Figure out colors for each index
norm = matplotlib.colors.Normalize(vmin=minIndex, vmax=maxIndex, clip=True)
mapper=cm.ScalarMappable(norm=norm, cmap='RdYlBu')

for key in indexList
    gridIndexDict[key] = mapper.to_rgba(indexList[key]) #

# Map to draw on, minX etc. won't interest here
m = Basemap(projection='merc', lat_0=(minX+maxX)/2, lon_0 = (minY+maxY)/2,
    resolution='h', area_thresh=0.1,llcrnrlon=minX, llcrnrlat=minY, 
    urcrnrlon=maxX, urcrnrlat=maxY)

# Yes, that's 1000 shapefiles
for i in range(0, 40):
    for j in range(0, 25):
        path = "Some path using i and j"
        m.readshapefile(path, "Title", color=gridIndexDict["Key using i and j"])

###
# I think this is the place to add a colorbar legend?
###
plt.show()

Basically I'm using the two loops to read and paint shapefiles with a previously determined color. The individual shapefiles are painted in the correct color, but I can't get the colorbar to even show up.

I've spent hours trying to dig through documentations and examples, but couldn't get anything to work. Maybe some of you can help me with this? Please let me know if I need to provide more information for you.

Upvotes: 0

Views: 884

Answers (1)

Verzweifler
Verzweifler

Reputation: 940

On behalf of @tcaswell, I write this answer in his stead:

mapper.set_array(indexList)
plt.colorbar(mapper)

works as well as

fig = plt.gcf()
mapper.set_array(indexList)
fig.colorbar(mapper)

Upvotes: 1

Related Questions