How can I get the position of a datapoint on a plot?
1 view (last 30 days)
Show older comments
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
Accepted Answer
Robert U
on 22 Sep 2017
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
More Answers (0)
See Also
Categories
Find more on Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!