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

5 ビュー (過去 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 Center および File ExchangeInteractive Control and Callbacks についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by