Use Double Array Values to Label Plot
7 views (last 30 days)
Show older comments
I have a variable 'xx' that is a 1x9 double. I want to use those values to label the points along the line in plot(t,xx)
This is my code
Ts = 1/8;
t = 0:Ts:1;
x = @(t) cos(2*pi*t-(pi/2));
xx = x(t);
labels = {'Sample 1', 'Sample 2', 'Sample 3', 'Sample 4', 'Sample 5', 'Sample 6', 'Sample 7', 'Sample 8', 'Sample 9'};
plot(t,xx,'rd-', 'linewidth', 1.5, 'MarkerSize', 9, 'MarkerFaceColor', 'w'), grid on
text(t,xx,labels)
2 Comments
Accepted Answer
dpb
on 28 Jan 2023
"Would making labels = string(xx) work?"
Did you try?
It works for a basic definition of what "working" might mean; you might find something like
text(t,xx,compose('%0.3f',xx))
more pleasing to the eye. Investigate the named parameters to text regarding position the text so as to not write on top of the data itself...
2 Comments
dpb
on 28 Jan 2023
Edited: dpb
on 29 Jan 2023
Try something more like
Ts = 1/8;
t = 0:Ts:1;
xx = cos(2*pi*t-(pi/2)); % no need for the anonymous function here...
plot(t,xx,'rd-', 'linewidth', 1.5, 'MarkerSize', 9, 'MarkerFaceColor', 'w'), grid on
ylim(1.2*ylim)
hold on
labels=compose('Sample: %d\n%0.3f',[1:numel(xx)].',xx.');
hT=text(t+0.025,xx+0.05,labels);
hT(end).HorizontalAlignment='right';
hT(end).Position=[1-0.025 0.1];
for starters. One can always be more clever about trying to locate where place annotations based on actual data and anything known a priori about shape of curve, etc., to minimize occluding data more than necessary.
The fixup here for the last position to place it to the left instead of the right owing to knowing it will run off the RH side otherwise, is one obvious nicety.
More Answers (0)
See Also
Categories
Find more on Graphics Performance 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!