是否可以在python中使用basemap来创建不透明(seethrough)映射?

2024-06-26 14:12:46 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以使用Python basemap(matplotlib)绘制填充颜色透明(半透明)的贴图?我正在构建一张澳大利亚郊区的热图,我最终打算用谷歌地图的图片覆盖它。因此,我希望填充颜色是半透明的。我的代码很长(250行),所以最好不要全部发布。如有任何建议,我将不胜感激。最有可能的是,它将colormap的alpha值设置为0到1之间的某个值。我正在使用Python的matplotlib basemap(如果这有帮助的话)。我还使用了这个网站的代码(它可能会帮助你理解我在做什么):http://brandonrose.org/pythonmap

# Convenience functions for working with color ramps and bars
def colorbar_index(ncolors, cmap, labels=None, **kwargs):
"""
This is a convenience function to stop you making off-by-one errors
Takes a standard colour ramp, and discretizes it,
then draws a colour bar with correctly aligned labels
"""
cmap = cmap_discretize(cmap, ncolors)
mappable = cm.ScalarMappable(cmap=cmap)
mappable.set_array([])
mappable.set_clim(-0.5, ncolors + 0.5)
colorbar = plt.colorbar(mappable, **kwargs)
colorbar.set_ticks(np.linspace(0, ncolors, ncolors))
colorbar.set_ticklabels(range(ncolors))
#colorbar.set_alpha(0.5)
if labels:
    colorbar.set_ticklabels(labels)
return colorbar


def cmap_discretize(cmap, N):
"""
Return a discrete colormap from the continuous colormap cmap.

    cmap: colormap instance, eg. cm.jet.
    N: number of colors.

Example
    x = resize(arange(100), (5,100))
    djet = cmap_discretize(cm.jet, 5)
    imshow(x, cmap=djet)

"""
if type(cmap) == str:
    cmap = get_cmap(cmap)
colors_i = np.concatenate((np.linspace(0, 1., N), (0., 0., 0., 0.)))
colors_rgba = cmap(colors_i)
indices = np.linspace(0, 1., N + 1)
cdict = {}
for ki, key in enumerate(('red', 'green', 'blue')):
    cdict[key] = [(indices[i], colors_rgba[i - 1, ki], colors_rgba[i, ki]) for i in xrange(N + 1)]
return matplotlib.colors.LinearSegmentedColormap(cmap.name + "_%d" % N, cdict, 1024)

Tags: forlabelsmatplotlibnpcmcmapcolorsset