mass communicating

Matlab Multicoloured Lines

It’s not actually hard, but still took me a while to do.

This…

>> tcline([1 2], [5 6], [1 0 0], [0 0 1], 'linewidth', 2)

… draws that:

plot

A side-effect is also that it can draw transparent lines (e.g. pass 'edgealpha', 0.5).

Here is the code, save into tcline.m.

function l = tcline(x, y, c1, c2, varargin)
% FUNCTION l = tcline(x, y, c1, c2, varargin)
% 
% Draws a colour-interpolated 2D-line from x to y
% 
% Parameters:
% 
%  x : [x1 x2] start point
%  y : [y1 y2] end point
%  c1: [r g b] colour of start point
%  c2: [r g b] colour of end point
%
%  anything else gets passed on to patch
% 
% Returns:
%  a patch object

xdata = [x(1)   ;
         y(1)   ;
         x(1)  ];
     
ydata = [x(2)   ;
         y(2)   ;
         x(2)   ];
cdata = zeros(3,1);
cdata(:,:,1) = [ c1(1)   ;
                 c2(1)   ;
                 c1(1)   ];
cdata(:,:,2) = [ c1(2)   ;
                 c2(2)   ;
                 c1(2)   ];
cdata(:,:,3) = [ c1(3)   ;
                 c2(3)   ;
                 c1(3)   ];
l = patch(xdata,ydata,cdata,...
      'EdgeColor', 'interp', ...
      'FaceColor', 'none', ...
      varargin{:});

end
Category: code Tags: matlab plotting