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

조회 수: 3 (최근 30일)
Pal Szabo
Pal Szabo 2017년 9월 21일
댓글: Pal Szabo 2017년 9월 22일
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?

채택된 답변

Robert U
Robert U 2017년 9월 22일
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
Pal Szabo
Pal Szabo 2017년 9월 22일
Great. It works indeed. Thank you!
Pal Szabo
Pal Szabo 2017년 9월 22일
Here I have a follow up question, if you happen to have time. :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by