I am using Matlab R2020b and I would like to display additional info when hovering the cursor over a data point in a 2D plot. I have values of angle and radius for a polarplot. Each data point is associated with a time. I create the plot similar to this:
t = linspace(0, 1, 100);
phi = 2*pi*t;
r = t.^2+1;
h = figure;
polarplot(phi, r, '-sb');
dcm = datacursormode(h);
datacursormode on;
set(dcm, 'updatefcn', @myfunction);
function output_txt = myfunction(obj,event_obj)
% Display data cursor position in a data tip
% obj Currently not used
% event_obj Handle to event object
% output_txt Data tip text, returned as a character vector or a cell array of character vectors
pos = event_obj.Position;
%********* Define the content of the data tip here *********%
% Display the x and y values:
output_txt = {['\phi: ' num2str(pos(1)*180/pi) '°'],...
['r: ' num2str(pos(2))]};
%***********************************************************%
% If there is a z value, display it:
if length(pos) > 2
output_txt{end+1} = ['Z',formatValue(pos(3),event_obj)];
end
%***********************************************************%
end
Ideally, I would like to have a triplet of (angle, radius, time) dispayed for any data point that I select. The information about custom data tips does not tell me how I can add values of another variable (time), only when using a 3D plot such as plot3.
Do you know any solution to this problem?
You want to have the time as a third value in your polarplot
when selecting data points, and to do this you can add the time (variable t
) to the ZData
property of the polarplot
.
To do this you want to use a handler for the polarplot axes, i.e. hax = polarplot(phi, r, '-sb');
so that you can put the time as ZData: hax.ZData = t;
. When you've done this, the variable pos
in myfunction
will have a length of 3 instead of 2 so your if
-statement will be executed.
Your updated code should look something like this:
t = linspace(0, 1, 100);
phi = 2*pi*t;
r = t.^2+1;
h = figure;
hax = polarplot(phi, r, '-sb'); % New code
hax.ZData = t; % New code
dcm = datacursormode(h);
datacursormode on;
set(dcm, 'updatefcn', @myfunction);
function output_txt = myfunction(obj,event_obj)
% Display data cursor position in a data tip
% obj Currently not used
% event_obj Handle to event object
% output_txt Data tip text, returned as a character vector or a cell array of character vectors
pos = event_obj.Position;
%********* Define the content of the data tip here *********%
% Display the x and y values:
output_txt = {['\phi: ' num2str(pos(1)*180/pi) '°'],...
['r: ' num2str(pos(2))]};
%***********************************************************%
% If there is a z value, display it:
if length(pos) > 2
output_txt{end+1} = ['Z',formatValue(pos(3),event_obj)];
end
%***********************************************************%
end
Let me know if it doesn't work :) Good luck!