我怎样才能像补丁面一样对补丁边缘进行着色(使用颜色图)?

How can I color patch edges like patch faces (using the colormap)?

我在一个图中有几个补丁(见下面的最小工作示例)。目前,这些补丁的面部颜色由 FaceVertexCData 确定,一个参考当前颜色条的标量,以及由 EdgeColor 确定的边缘颜色,一个 RGB 向量。我想要做的是删除面部颜色并使边缘与各自补丁的原始面部颜色相同。

使用 FaceAlpha 属性 去除面部颜色很简单,但我似乎无法弄清楚如何将 FaceVertexCData 属性 变成它的等价物RGB 代码,以便我可以将其分配给 EdgeColor

h.fig = figure;
h.patch(1) = patch([0 1 1 0],[0 0 .3 .3],10);
h.patch(2) = patch([0 1 1 0],[.5 .5 .9 .9],5);
set(h.patch, 'FaceAlpha', 0);

先获取当前的colormap和colorbar

currentCmap = colormap; % get the current colormap
theColorbar = colorbar; % get the current colorbar

然后在颜色栏中找到 cdata 值(可能有更好的方法)。

colorVertexList = linspace(theColorbar.Limits(1), theColorbar.Limits(2), size(currentCmap, 1));

为了在上面的列表中找到补丁颜色的索引,我只使用最小的差异,如下所示

[~, patch1ColorIndex] = min(abs(h.patch(1).FaceVertexCData-colorVertexList));
[~, patch2ColorIndex] = min(abs(h.patch(2).FaceVertexCData-colorVertexList));

然后您可以从颜色图中获取 rgb 值

patch1Color = currentCmap(patch1ColorIndex, :);
patch2Color = currentCmap(patch2ColorIndex, :);

并设置颜色

set(h.patch, 'FaceAlpha', 0);
set(h.patch(1), 'EdgeColor', patch1Color);
set(h.patch(2), 'EdgeColor', patch2Color);

对于未来的用户,我已经将 Vahe Tshitoyan 的解决方案实现为一个函数。

function RGB = cdata2rgb(ax,val)
% CDATA2RGB convert cdata values to their corresponding RGB vector.
%   RGB = cdata2rgb(ax,val) converts the values in n-by-1 vector val to
%   an n-by-3 RGB matrix. Uses the colormap and colorbar associated with
%   axis handle ax. 
h.cmap = colormap(ax);

CDataList = linspace(ax.CLim(1), ax.CLim(2), size(h.cmap, 1));

[~, idx] = min(abs(val-CDataList),[],2); %Change to bsxfun if implicit expansion is not supported. 
RGB = h.cmap(idx,:);

end

这就是我的最终代码:

h.fig = figure;
h.ax = axes();
h.patch(1) = patch([0 1 1 0],[0 0 .3 .3],10);
h.patch(2) = patch([0 1 1 0],[.5 .5 .9 .9],5);
set(h.patch, 'FaceAlpha', 0);
set(h.patch(1), 'EdgeColor', cdata2rgb(h.ax,h.patch(1).FaceVertexCData));
set(h.patch(2), 'EdgeColor', cdata2rgb(h.ax,h.patch(2).FaceVertexCData));

有一种非常简单的方法可以为边缘着色。如果您将 color data the same size as your vertex data (i.e. the X and Y arguments), you can set the 'EdgeColor' property 设置为 'flat' 以便它使用颜色图中的插值颜色值:

h.fig = figure;
h.patch(1) = patch([0 1 1 0], [0 0 .3 .3], 10.*ones(1, 4));
h.patch(2) = patch([0 1 1 0], [.5 .5 .9 .9], 5.*ones(1, 4));
set(h.patch, 'FaceColor', 'none', 'EdgeColor', 'flat');