在旧的图形系统(R2014a及更早版本)中,这是不可能使用内置的颤抖对象.您可以轻松获取用于组成颤抖图的所有绘图对象
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;
然后,您可以更改这些对象的颜色属性,使每个箭头不同的颜色.
基本思想
为此,我首先计算所有颤抖箭头的大小(这适用于颤抖和颤抖3)
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);
LineStrip ColorData属性(当指定为truecolor时)也需要有一个Alpha通道(我们将设置为255,意思是不透明).
cmap(:,:,4) = 255;
此时,我们可以将ColorBinding属性设置为内插而不是对象(将其与抖动对象分离),并将q.Head和q.Tail的ColorData属性设置为上述我们创建的颜色,使每个箭头都是自己的颜色.
完整解决方案
注意:此解决方案适用于颤抖和颤抖3,代码不需要进行调整.
%// 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).');
并应用于二维抖动对象
如果您不一定要将箭头缩放到色彩映射的整个范围,您可以使用以下对histcounts的调用(而不是上面的行)来使用轴的颜色限制映射大小.
clims = num2cell(get(gca, 'clim'));
[~, ~, ind] = histcounts(mags, linspace(clims{:}, size(currentColormap, 1)));