Use Double Array Values to Label Plot
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
collegestudent
el 28 de En. de 2023
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 comentarios
cdawg
el 28 de En. de 2023
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)
Respuesta aceptada
dpb
el 28 de En. de 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 comentarios
cdawg
el 28 de En. de 2023
@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
el 28 de En. de 2023
Editada: dpb
el 29 de En. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Axis Labels en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!