Matplotlib ScalarMappable:如果设置了规范,为什么需要set_array()? [英] Matplotlib ScalarMappable: why need to set_array() if norm set?

查看:87
本文介绍了Matplotlib ScalarMappable:如果设置了规范,为什么需要set_array()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用颜色图绘制一组多边形.我设置了一个ScalarMappable对象,并从该ScalarMappable生成多边形颜色,但是当我尝试添加颜色栏时,出现错误:

I'm trying to plot a set of polygons with a colormap. I set up a ScalarMappable object and generate polygon colors from that ScalarMappable, but when I try to add a colorbar, I get the error:

TypeError: You must first set_array for mappable

set_array"的文档并没有真正说明什么,所以我完全不清楚它在做什么,我是否需要给它赋值,如果我这样做了,他们会做什么.

The documentation for "set_array" doesn't really say anything, so I'm not at all clear what it is doing, whether I need to give it values, and if I do, what they will be doing.

谁能解释一下 set_array 的作用,以及我应该如何处理?

Can anyone please explain what set_array does, and how I should deal with this?

    plt.clf()
    fig, ax  = plt.subplots(1,1)

    # Set color mappable
    range_min = df.col1.min()
    range_max = df.col1.max()
    cmap = matplotlib.cm.ScalarMappable(
          norm = mcolors.Normalize(range_min, range_max), 
          cmap = plt.get_cmap('binary'))

    for i in polygonDict.keys():
        ax.add_patch(ds.PolygonPatch(polygonDict[i], fc = cmap.to_rgba(df.col1.loc[i])))

    fig.colorbar(cmap, ax = ax)

推荐答案

一种简单的方法是将一个空数组 [] 发送到 set_array().我真的不知道为什么,但是我已经在此答案中看到了它的完成,并且有效.

A far easier way to do this is to send an empty array [] to set_array(). I don't really know why, but I've seen it done in this answer, and it works.

我唯一了解的是,在设置数组之前,您会从 get_array()中得到 None ,这可能就是您收到此错误的原因.

The only thing I know is that before you set the array, you get None from get_array(), which is probably why you get this error.

您可以:

plt.clf()
fig, ax  = plt.subplots(1,1)

# Set color mappable
range_min = df.col1.min()
range_max = df.col1.max()
cmap = matplotlib.cm.ScalarMappable(
      norm = mcolors.Normalize(range_min, range_max), 
      cmap = plt.get_cmap('binary'))

for i in polygonDict.keys():
    ax.add_patch(ds.PolygonPatch(polygonDict[i], fc = cmap.to_rgba(df.col1.loc[i])))

cmap.set_array([]) # or alternatively cmap._A = []

fig.colorbar(cmap, ax = ax)

经过几次测试,您似乎可以将世界上的任何数组([df.col1],[0,1],['hello'])发送到 set_array(),您的颜色条将是您想要的颜色条.只是不能 None .

After a few tests, it seems that you can send any array in the world ([df.col1], [0,1], ['hello']) to set_array(), and your colorbar will be the one you want. It just can't be None.

我注意到,如果您将数组设置为数字数组,然后调用 autoscale(),颜色条的最小值和最大值将是该数组的最小值和最大值.

I've noticed that if you set the array to an number array, and then call autoscale(), the min and max values of the colorbar will be the min and max of that array.

我希望这会有所帮助.

这篇关于Matplotlib ScalarMappable:如果设置了规范,为什么需要set_array()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆