如何让用户选择颜色图?

How to let user pick colormap?

大家好我想定义一个函数来绘制地图,这里是一个简单的例子:

def PlotMap(df, fig = plt.figure(), size = 111, loc_ix = 0):
    ax = fig.add_subplot(size + loc_ix)
    color = matplotlib.cm.spectral(np.linspace(0,1,100))
    for s in df.index:
#this is for plotting process
#extract polygon from data frame df
        poly = Polygon(df.polygon[s])
#find its color based on the partition
        c = color[df.partition[s]][0:3]
        ax.add_patch(PolygonPatch(poly, fc = c, ec = 'k', alpha = 0.7, zorder = 2))
    ax.axis('scaled')

你看到这里的颜色是用 'spectral' 固定的,我想知道如何修改这段代码,以便用户可以选择他们喜欢的颜色图?理想的情况是添加一个额外的输入参数(我们称之为 cmap),然后我们可以简单地调用

PlotMap(df, cmap = 'hot')

绘制热图。 ('spectral' 是默认设置。)

非常感谢!

是这样的吗?

color_map_name = "spectral"
color_func = getattr(matplotlib.cm, color_map_name)
color = color_func(np.linspace(0,1,100))

编辑:更好:

color_func = matplotlib.cm.get_cmap(color_map_name)