使用 matplotlib 的 set_array() 例程的指南是什么?

Joh*_*ong 10 python matplotlib color-mapping

的文档set_array非常少。它有什么作用?它可以采用什么范围的值?它如何与其他与颜色相关的例程和数据结构结合使用?

集合文档页面上,据说“从 numpy 数组 A 设置图像数组”。它在colormap API中以相同的方式描述。就这样。

我发现set_array()在关于 matplotlib 编程的几本流行书中都没有提到(更少的例子),例如 Devert (2014)、McGreggor (2015)、Root (2015) 和 Tossi (2009)。

然而,如果set_array()有一些只在极少数情况下需要的神秘函数,为什么它会在 matplotlib 示例和 SciKit Learn 网站上发布的示例中如此频繁地出现?看起来是一个相当主流的功能,所以它应该有更多的主流文档。

例如:

筛选 Stack Overflow 上提到的帖子,set_array()我发现了这个帖子,其中一张海报指出“set_array()处理将一组数据值映射到 RGB”,而这个海报表明set_array()在某些情况下必须在设置ScalarMappable对象时调用它。

我尝试过使用我在网上找到的示例,更改传入 的值范围set_array(),例如,试图弄清楚它在做什么。但是,在这一点上,我在这个愚蠢的功能上花费了太多时间。那些深入了解彩色地图的人有足够的上下文来猜测它的作用,但我不能走那么大的弯路,只是为了理解这个功能。

有人可以提供一个快速描述和一些链接吗?

moz*_*way 1

该方法本身set_array并没有做太多事情。它仅定义定义它的对象内部的数组内容。例如,参见matplotlib.cm的源代码

def set_array(self, A):
    """
    Set the image array from numpy array *A*.

    Parameters
    ----------
    A : ndarray
    """
    self._A = A
    self._update_dict['array'] = True
Run Code Online (Sandbox Code Playgroud)

matplotlib 文档的 multicolored_line 示例中,这用于映射 cmap 的颜色。

让我们举一个类似的例子,创建一个线条集合,并将这些线段映射到颜色图中的索引颜色:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm

f, axes = plt.subplots(ncols=3)

y = np.arange(0,1,0.1).repeat(2)
x = np.append(y[1:], [1])
segments = np.array(list(zip(x,y))).reshape(-1, 2, 2)

cmap = ListedColormap(['r', 'g', 'b'])
norm = BoundaryNorm([-0.5, 0.5, 1.5, 2.5], cmap.N)

for ax in axes:
    ax.add_collection(LineCollection(segments, cmap=ListedColormap(['r', 'g', 'b']), norm=norm))
    
axes[1].collections[0].set_array(np.array([0,1]))
axes[2].collections[0].set_array(np.array([0,1,2]))

axes[1].set_title('set_array to [0,1]')
axes[2].set_title('set_array to [0,1,2]')
Run Code Online (Sandbox Code Playgroud)

这给出了以下输出:

使用 set_array 映射 cmap

它的作用是将段映射到 cmap 中定义的索引颜色(此处为 0->'r'、1->'g'、2->'b')。此行为在matpotlib.collections源中指定:

Each Collection can optionally be used as its own `.ScalarMappable` by
passing the *norm* and *cmap* parameters to its constructor. If the
Collection's `.ScalarMappable` matrix ``_A`` has been set (via a call
to `.Collection.set_array`), then at draw time this internal scalar
mappable will be used to set the ``facecolors`` and ``edgecolors``,
ignoring those that were manually passed in.
Run Code Online (Sandbox Code Playgroud)