MATLAB Answers

0

How can I get the position of a datapoint on a plot?

Asked by Pal Szabo on 21 Sep 2017
Latest activity Commented on by Pal Szabo on 22 Sep 2017
I have the following code:
x=[1:1:5]
a=rand*10
y=[2,a,3,5,4]
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
plot(x,y)
hold on
plot(2,a,'.','markersize',40)
% Create and display the text label
url = 'cam.ac.uk';
labelStr = ['<html><a href="">' 'SPEC' '</a></html>'];
jLabel = javaObjectEDT('javax.swing.JLabel', labelStr);
[hjLabel,hContainer] = javacomponent(jLabel, [1000,800,30,20], gcf);
% WHAT SHOULD [1000, 800, 30, 20] BE IF I WANT THE LABEL TO BE AT THE SAME
% POSITION AS THE DOT ON THE PLOT?
% Modify the mouse cursor when hovering on the label
hjLabel.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.HAND_CURSOR));
% Set the label's tooltip
hjLabel.setToolTipText(['Visit the ' url ' website']);
% Set the mouse-click callback
set(hjLabel, 'MouseClickedCallback', @(h,e)web(['http://' url], '-browser'))
How can I get the position of the point which is plotted randomly? Now it looks like this:
I want the "SPEC" hyperlink to appear just next to the randomly plotted point. How can I do that?

  0 Comments

Sign in to comment.

1 Answer

Answer by Robert U
on 22 Sep 2017
 Accepted Answer

Hi Pal Szabo,
that should do what you desired:
x=[1:1:5];
a=rand*10;
y=[2,a,3,5,4];
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
plot(x,y)
hold on
plot(2,a,'.','markersize',40)
% Create and display the text label
url = 'cam.ac.uk';
labelStr = ['<html><a href="">' 'SPEC' '</a></html>'];
jLabel = javaObjectEDT('javax.swing.JLabel', labelStr);
% Adjust label position
ah = gca;
set(ah,'Units','pixels')
axesPos = get(ah,'Position');
drawnow(); % necessary to fix the axes positions
Px = round(ah.Position(1) + ah.Position(3)*(2-ah.XLim(1))/(ah.XLim(2)-ah.XLim(1))); % x-position is alway 2
Py = round(ah.Position(2) + ah.Position(4)*(a-ah.YLim(1))/(ah.YLim(2)-ah.YLim(1)));
[hjLabel,hContainer] = javacomponent(jLabel, [Px-30/2,Py+10,30,20], gcf); % center for x, move 5px above y
set(ah,'Units','normalized')
% Modify the mouse cursor when hovering on the label
hjLabel.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.HAND_CURSOR));
% Set the label's tooltip
hjLabel.setToolTipText(['Visit the ' url ' website']);
% Set the mouse-click callback
set(hjLabel, 'MouseClickedCallback', @(h,e)web(['http://' url], '-browser'))
Kind regards,
Robert

  2 Comments

Great. It works indeed. Thank you!
Here I have a follow up question, if you happen to have time. :)

Sign in to comment.