在旧的图形系统(R2014a 和更早版本)中,使用内置的quiver 对象是不可能的。您可以轻松获取用于构成quiver 绘图的所有绘图对象
q = quiver(1:5, 1:5, 1:5, 1:5);
handles = findall(q, 'type', 'line');
但尾巴都由一个绘图对象表示,箭头由另一个表示。因此,您不能单独更改每个头/尾的颜色。
set(handles(1), 'Color', 'r')
set(handles(2), 'Color', 'g')
但是,随着 HG2(R2014b 及更高版本)的引入,您实际上可以访问 两个(未记录)LineStrip 对象 (matlab.graphics.primitive.world.LineStrip)(一个代表头部,一个代表尾巴)。这些可以通过隐藏属性Tail 和Head 访问。
q = quiver(1, 1, 1, 1);
headLineStrip = q.Head;
tailLineStrip = q.Tail;
然后您可以更改这些对象的颜色属性,使每个箭头具有不同的颜色。
基本理念
为此,我首先计算所有箭袋的大小(这适用于quiver 和quiver3)
mags = sqrt(sum(cat(2, q.UData(:), q.VData(:), ...
reshape(q.WData, numel(q.UData), [])).^2, 2));
然后我使用当前颜色图将每个幅度映射到一个 RGB 值。最短的箭头被分配颜色图上的最低颜色,最长的箭头被分配颜色图上的最高颜色。 histcounts 非常适合为每个幅度分配一个索引,该索引可以与颜色图本身一起传递给ind2rgb。我们必须乘以 255,因为我们需要颜色为 RGB 作为 8 位整数。
% Get the current colormap
currentColormap = colormap(gca);
% Now determine the color to make each arrow using a colormap
[~, ~, ind] = histcounts(mags, size(currentColormap, 1));
% Now map this to a colormap
cmap = uint8(ind2rgb(ind(:), currentColormap) * 255);
LineStripColorData 属性(当指定为 truecolor 时)还需要有一个 Alpha 通道(我们将其设置为 255 表示不透明)。
cmap(:,:,4) = 255;
此时,我们可以将ColorBinding 属性设置为interpolated 而不是object(将其与quiver 对象分离)并设置q.Head 和@987654352 的ColorData 属性@ 为我们在上面创建的颜色赋予每个箭头它自己的颜色。
完整解决方案
注意:此解决方案都适用于quiver 和quiver3,代码根本不需要修改。
%// Create a quiver3 as we normally would (could also be 2D quiver)
x = 1:10;
y = 1:10;
[X,Y] = meshgrid(x, y);
Z = zeros(size(X));
U = zeros(size(X));
V = zeros(size(X));
W = sqrt(X.^2 + Y.^2);
q = quiver3(X, Y, Z, U, V, W);
%// Compute the magnitude of the vectors
mags = sqrt(sum(cat(2, q.UData(:), q.VData(:), ...
reshape(q.WData, numel(q.UData), [])).^2, 2));
%// Get the current colormap
currentColormap = colormap(gca);
%// Now determine the color to make each arrow using a colormap
[~, ~, ind] = histcounts(mags, size(currentColormap, 1));
%// Now map this to a colormap to get RGB
cmap = uint8(ind2rgb(ind(:), currentColormap) * 255);
cmap(:,:,4) = 255;
cmap = permute(repmat(cmap, [1 3 1]), [2 1 3]);
%// We repeat each color 3 times (using 1:3 below) because each arrow has 3 vertices
set(q.Head, ...
'ColorBinding', 'interpolated', ...
'ColorData', reshape(cmap(1:3,:,:), [], 4).'); %'
%// We repeat each color 2 times (using 1:2 below) because each tail has 2 vertices
set(q.Tail, ...
'ColorBinding', 'interpolated', ...
'ColorData', reshape(cmap(1:2,:,:), [], 4).');
并应用于 2D quiver 对象
如果您不一定要将箭头缩放到颜色图的整个范围,您可以使用以下对histcounts 的调用(而不是上面的行)来使用轴的颜色限制来映射幅度。
clims = num2cell(get(gca, 'clim'));
[~, ~, ind] = histcounts(mags, linspace(clims{:}, size(currentColormap, 1)));