8

I have two two-by-n arrays, representing 2d-points. These two arrays are plotted in the same figure, but in two different subplots. For every point in one of the arrays, there is a corresponding point i the other array. I want to show this correspondance by drawing a line from one of the subplots to the other subplot.

The solutions i have found are something like:

 ah=axes('position',[.2,.2,.6,.6],'visible','off'); % <- select your pos...
 line([.1,.9],[.1,.9],'parent',ah,'linewidth',5);

This plots a line in the coordinate system given by the axes call. In order for this to work for me i need a way to change coordinate system between the subplots system and the new system. Anybody know how this can be done?

Maybe there is different way of doing this. If so i would love to know.

PKeno
  • 2,694
  • 7
  • 20
  • 37

2 Answers2

8

First you have to convert axes coordinates to figure coordinates. Then you can use ANNOTATION function to draw lines in the figure.

You can use Data space to figure units conversion (ds2nfu) submission on FileExchange.

Here is a code example:

% two 2x5 arrays with random data
a1 = rand(2,5);
a2 = rand(2,5);

% two subplots
subplot(211)
scatter(a1(1,:),a1(2,:))
% Convert axes coordinates to figure coordinates for 1st axes
[xa1 ya1] = ds2nfu(a1(1,:),a1(2,:));


subplot(212)
scatter(a2(1,:),a2(2,:))
% Convert axes coordinates to figure coordinates for 2nd axes
[xa2 ya2] = ds2nfu(a2(1,:),a2(2,:));

% draw the lines
for k=1:numel(xa1)
    annotation('line',[xa1(k) xa2(k)],[ya1(k) ya2(k)],'color','r');
end

Make sure your data arrays are equal in size.

Edit: The code above will do data conversion for a current axes. You can also do it for particular axes:

hAx1 = subplot(211);
% ...
[xa1 ya1] = ds2nfu(hAx1, a1(1,:),a1(2,:));
yuk
  • 19,098
  • 13
  • 68
  • 99
  • 1
    Does not work for me: the lines are drawn from one `subplot` to the other, but they do not link the points. Moreover, when I resize the figure, the lines change their relative positions... – Shai May 16 '13 at 10:56
  • I think it's the bug in the submitted script. @Shai – SolessChong Apr 23 '14 at 02:32
  • Just noticed @Shai comment. It might be necessary to set proper units for the figure before applying ds2nfu. – yuk Apr 23 '14 at 14:51
  • Interestingly, the code above works only if I don't set the Units property for the figure at all. If I set it even to the default one (pixels) the lines do not line up with the points. Strange... – yuk Apr 23 '14 at 18:27
-2

A simple solution is to use the toolbar in the figure window. Just click "insert" and then "Line".

Ghaul
  • 3,340
  • 1
  • 19
  • 24