MATLAB: Datacursormode: how to permanently turn on “make new data tip”

datacursormodeMATLAB and Simulink Student Suitenew data tip.undocumented

Hello! I want to select multiple data points on figure using data cursor (shift + click). Can this functionality be turned on programmatically in a way that there is no need for holding shift? Thank you for any advice!

Best Answer

Although the official documentation of the datacursormode function says explicitly that:
"You place data tips only by clicking data objects on graphs. You cannot place them programmatically (by executing code to position a data cursor)."
This is in fact WRONG AND MISLEADING, as I explained far back in 2011: https://undocumentedmatlab.com/blog/controlling-plot-data-tips
The general solution for your specific request:
1. First, set the plot line's button-down function to a custom callback function:
hLine = plot(...);
set(hLine, 'ButtonDownFcn', @lineClickedCallback);
2. Next, implement this callback function that will add the requested data-tip at the clicked location:
function lineClickedCallback(hLine, eventData)
% Get the clicked position from the event-data
pos = eventData.IntersectionPoint;
% Get the line's containing figure
hFig = ancestor(hLine,'figure');
% Get the figure's datacursormode object
cursorMode = datacursormode(hFig);
% Create a new data-tip at the clicked location
hDatatip = cursorMode.createDatatip(hLine);
set(hDatatip, 'Position',pos, 'MarkerSize',5, 'MarkerFaceColor','none', 'MarkerEdgeColor','r', 'Marker','o', 'HitTest','off');
end
You can modify this code to make the data-tip and/or marker look different.