How do I continuously update a figure axis with time values using animatedline?

15 views (last 30 days)
This code is intended to collect speed data and timestamps from a serial port device in real time and plot speed as a function of time. The plotting code inside the loop is as follows:
timestring = convertCharsToStrings(datestr(time/24, 'HH:MM:SS'));
figure(1)
subplot(2,2,3)
hold on
addpoints(speed_line, time, speed_mph)
drawnow()
set(gca, 'Xtick', time, 'XTickLabel', timestring);
xlabel('Time (EDT)')
ylabel('Speed (mph)')
The problem with this code is that the x-axis only shows the most recently collected timestamp. A photo of this is attached below. I would like the x-axis to show multiple timestamps (either at every minute or otherwise evenly spaced along the axis). How could this be accomplished? Additionally, is it possible to make the plot scroll from left to right to only display the most recently collected data?
Thanks in advance!
  1 Comment
Siddharth Bhutiya
Siddharth Bhutiya on 28 Jul 2022
Can you add a sample code that I can run on my side? You create dummy values for the variables in the code sample itself or attach a mat file.
On a side note, I see that you are using datestr. datestr is a legacy function which is not longer recommended, instead try using datetimes and if you need to convert those to text you can simply do string(dt).

Sign in to comment.

Answers (1)

Steven Lord
Steven Lord on 28 Jul 2022
The problem with this code is that the x-axis only shows the most recently collected timestamp.
That is the correct behavior as you've written it. Run these two examples in your MATLAB session (since MATLAB Answers won't show you the animation.)
x = 1:10;
y = x.^2;
figure('Name', 'Update ticks with most recent value only')
h = animatedline('Marker', 'o');
for k = 1:10
addpoints(h, x(k), y(k));
xticks(x(k))
xticklabels(string(x(k)))
pause(0.5) % So you can see the change
end
figure('Name', 'Update ticks with all values up to and including most recent value')
h = animatedline('Marker', 'o');
for k = 1:10
addpoints(h, x(k), y(k));
xticks(x(1:k)) % The difference is here
xticklabels(string(x(1:k))) % and here
pause(0.5) % So you can see the change
end

Categories

Find more on Animation in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!