如何让用户选择colormap?

时间:2016-04-29 14:24:56

标签: python matplotlib plot 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')

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

PlotMap(df, cmap = 'hot')

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

非常感谢!

1 个答案:

答案 0 :(得分:0)

这样的东西?

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)