Text in plot that has x-axis in terms of datetime

7 ビュー (過去 30 日間)
George Mathai
George Mathai 2015 年 9 月 1 日
回答済み: Steven Lord 2025 年 7 月 8 日
Hello,
I have a plot that uses a datetime structure as an x axis and I want to add a text string on my plot. Typically I would do that using text(x,y,'text'). In this case I am not sure what I would use as 'x'. The 'annotation' command uses normalized values that do not move when I zoom or pan the plot. Would appreciate some input on what I would use as my 'x' in the text function. Thanks!

採用された回答

Ricardo
Ricardo 2016 年 6 月 21 日
I just had this problem and I could position the text using datenum in this way:
text(datenum( the_date ), y_axis_val, text)
  1 件のコメント
Dick Benson
Dick Benson 2025 年 7 月 8 日
Excellent .... too simple !

サインインしてコメントする。

その他の回答 (2 件)

dpb
dpb 2015 年 9 月 2 日
A date number of the time x. Same idea as with ordinary axes; the date axes is one with the limits based on the first/last date of the x vector. You can retrieve these from the plot as
xlohi=xlim;
then scale between those two at whatever point you wish would be one way...
  2 件のコメント
George Mathai
George Mathai 2015 年 9 月 2 日
Thanks!
dpb
dpb 2015 年 9 月 2 日
If (as I presume given the comment) this solved the problem, please "ACCEPT" the answer -- besides my ego, it notifies other users who find the question the answer was considered/is a good 'un, thereby (hopefully) helping fulfill the idea of the forum in being a database repository...

サインインしてコメントする。


Steven Lord
Steven Lord 2025 年 7 月 8 日
Don't use datenum anymore. It is not recommended. Instead, use ruler2num or num2ruler to convert the datetime data into coordinates the text function can accept.
x = 1:10;
d = datetime(2025, 7, x);
y = x.^2;
h = plot(d, y);
value = ruler2num(d(5), gca().XAxis); % Convert July 5th to a number
text(value, 25, 'here')
grid on
The call gca().XAxis is a reference to the X axis of the current axes. ruler2num needs to know which ruler's coordinate system you're trying to convert into. If I wanted to be a little more careful (since which axes is the current axes can change easily, with a click in a different location in the figure or on a different figure) I could use the ancestor function to get the axes ancestor of the line created by plot. This is independent of which axes is current.
figure
h = plot(d, y);
ax = ancestor(h, 'axes');
value = ruler2num(d(7), ax.XAxis); % Remember d(7) is July 7th
text(value, 20, "y = 20 on July 7th")
grid on
You can see that the "y" starting the text lines up with July 7th (d(7)) on the X axis.

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by