Use Double Array Values to Label Plot
조회 수: 15 (최근 30일)
이전 댓글 표시
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
cdawg
2023년 1월 28일
Would making labels = string(xx) work?
Ts = 1/8;
t = 0:Ts:1;
x = @(t) cos(2*pi*t-(pi/2));
xx = x(t);
labels = string(xx);
plot(t,xx,'rd-', 'linewidth', 1.5, 'MarkerSize', 9, 'MarkerFaceColor', 'w'), grid on
text(t,xx,labels)
채택된 답변
dpb
2023년 1월 28일
"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
cdawg
2023년 1월 28일
@dpb is right, it does look much better. If you want to include the sample number in there as well, try something like this
Ts = 1/8;
t = 0:Ts:1;
x = @(t) cos(2*pi*t-(pi/2));
xx = x(t);
for ii = 1:length(xx)
label{ii} = sprintf('Sample %d: %0.3f', ii, xx(ii));
end
figure();
plot(t,xx,'rd-', 'linewidth', 1.5, 'MarkerSize', 9, 'MarkerFaceColor', 'w'), grid on
text(t,xx,label)
I'm sure there's an easier way to do it without a for loop...
And again dpb is right- as you can see the positioning of the labels doesn't look very good. You'll have to mess around with the location of the labels (or add the Sample label and the data label separately..)
dpb
2023년 1월 28일
편집: dpb
2023년 1월 29일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!