Interactive plotting

Example of interactive plotting: moving the mouse finds the closest data point, visually enhances it and floats a label at the mouse position. The main points are
function labeller

global data_x data_Y marker_cells colors overlay_ax
data_x = (-1:0.1:1)';
data_Y = [data_x data_x.^2 data_x.^3]
marker_cells{1} = 'o'; % as many cells as there are columns in data_Y
marker_cells{2} = 'x';
marker_cells{3} = 'v';
colors = [0 0 0; 1 0 0; 0 1 1]; % as many rows as there are columns in data_Y

figure;
set(gcf, 'DoubleBuffer', 'on');
set(gcf, 'WindowButtonMotionFcn', @movefunc);
plot_iets;
overlay_ax = axes('Position',get(gca,'Position'),...
           'XAxisLocation','top',...
           'YAxisLocation','right',...
           'Color','none',...
           'XColor','k','YColor','k',...
            'XLim', get(gca,'XLim'),...
            'YLim', get(gca,'YLim'));

function plot_iets
global data_x data_Y marker_cells colors
p0 = plot(data_x, data_Y);
for n = 1:size(data_Y, 2),
    set(p0(n), 'Marker', marker_cells{n});
    set(p0(n), 'Color', colors(n, :));
end;

function movefunc(varargin)
global data_x data_Y marker_cells colors overlay_ax
axes(overlay_ax);
pos = get(gca, 'CurrentPoint');
x = pos(1, 1);
y = pos(1, 2);
afstand = [];
index_closest = [];
for v = 1:size(data_Y, 2),
    afstanden_x = (data_x - x) .^ 2;
    afstanden_y = (data_Y(:, v) - y) .^ 2;
    afstanden = sqrt(afstanden_x + afstanden_y);
    [afstand(v), index_closest(v)] = min(afstanden);
end;
[minv, indexv] = min(afstand);
nearest_x = data_x(index_closest(indexv));
nearest_y = data_Y(index_closest(indexv), indexv);
cla;
p0 = line(nearest_x, nearest_y);
set(p0, 'LineWidth', 3);
set(p0, 'Marker', marker_cells{indexv});
set(p0, 'MarkerSize', 10);
set(p0, 'Color', colors(indexv, :));
text(x, y, [num2str(nearest_x) ' ' num2str(nearest_y)]);