将Colorbar图例添加到包含多个shapefile的Basemap图

时间:2016-05-01 16:05:45

标签: python matplotlib legend shapefile matplotlib-basemap

我正在使用Basemap将几个shapefile绘制到一个画布上,用之前计算过的索引着色。现在我正在尝试在我的图像旁边添加一个图例(颜色条),但我无法让它工作。到目前为止,这是我的代码:

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()

基本上我正在使用两个循环来读取和绘制具有先前确定的颜色的shapefile。各个shapefile都以正确的颜色绘制,但我无法让颜色条显示出来。

我花了好几个小时试图挖掘文档和示例,但无法获得任何工作。 也许有些人可以帮我这个?如果我需要为您提供更多信息,请与我们联系。

1 个答案:

答案 0 :(得分:1)

我代表@tcaswell代替他写下这个答案:

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

一样有效
fig = plt.gcf()
mapper.set_array(indexList)
fig.colorbar(mapper)