Clear Filters
Clear Filters

I having trouble displaying each value next to the correct data point on stem plot.

12 views (last 30 days)
I have an array of 1x20 containing the peak amplitude values and instead of displaying each text value next to the correct data point, it prints the entire array contents next to every data point.
PC = {0, NaN, -34.30, -39.90, -46.20, -47.80, -55.20, -52.20, -56.80, -60.90, -70.80, NaN, NaN, NaN, NaN, -72.80, NaN, NaN, NaN, NaN}
x=1:1:20;
subplot(3,1,3);
stem(x,RC);
text=text(x, RC, sprintf('%6.3f', RC));
set(text,'Rotation',60,'HorizontalAlignment','left','VerticalAlignment','baseline');
grid;
xlim([0, 20]);
title('Relative contribution of each harmonic ')
xlabel('Odd Harmonics');
ylabel('Contribution');

Accepted Answer

Star Strider
Star Strider on 16 Jun 2020
You can avoid the loop by using compose (or the undocumented sprintfc).
PC = {0, NaN, -34.30, -39.90, -46.20, -47.80, -55.20, -52.20, -56.80, -60.90, -70.80, NaN, NaN, NaN, NaN, -72.80, NaN, NaN, NaN, NaN}
x = 1:numel(PC);
figure
stem(x, [PC{:}], 'filled')
grid
xlim([0 20])
lbls = compose('%.2f', [PC{:}]);
text(x, [PC{:}], lbls, 'HorizontalAlignment','center', 'VerticalAlignment','top', 'FontSize',8)

More Answers (1)

Image Analyst
Image Analyst on 16 Jun 2020
I had made up this answer to your duplicate question, when you deleted it and I couldn't post it. So here it is:
v = rand(1, 40);
plot(v, 'b-', 'LineWidth', 2);
grid on;
[peakValues, indexesOfPeaks] = findpeaks(v);
hold on;
stem(indexesOfPeaks, peakValues, 'r.', 'LineWidth', 2, 'MarkerSize', 35);
for k = 1 : length(peakValues)
textLabel = sprintf('(%d, %.2f)', indexesOfPeaks(k), peakValues(k));
% Place text above the point by adding a little bit to the y value.
text(indexesOfPeaks(k), peakValues(k) + 0.05, textLabel, ...
'HorizontalAlignment', 'center', ...
'FontWeight', 'bold', ...
'FontSize', 12, ...
'Color', 'r');
end
We can't run the code you posted here because you didn't include RC, only PC. And if we change PC to RC, it still doesn't run.
Basically you need to put text() into a loop where you put up only one at a time.
  1 Comment
Michael Andersson
Michael Andersson on 17 Jun 2020
Thanks, I think I will use this method for some of the other data I need to analyse and display. Sorry if my posting is a bit hard to follow, this is the first question I have ever posted.

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!