Plotting a text file with time on x axis?

20 views (last 30 days)
Cheyanne
Cheyanne on 22 Nov 2025 at 14:41
Edited: dpb on 22 Nov 2025 at 16:03
I am plotting an ECG graoh using values from a text file and want to change the x axis to be time instead of a sample number. defining a time and trying to plot hasnt worked so far. I was wanting it to start at time zero and each data point be pointed at a particular sample time?
My code so far:
%Read the ECG file in
file=readtable("C:\Users\NAME\Documents\ECG_40.txt");
plot(file.Var1)
title('ECG Plot')
xlabel('Time/ms')
ylabel('Voltage/mV')
grid on
%Show R Peaks
[pks, locs] = findpeaks(file.Var1, 'MinPeakHeight', 400);
plot(file.Var1);
hold on;
plot(locs, pks, 'x'); % add 'x' markers at peak positions
grid on

Answers (1)

dpb
dpb on 22 Nov 2025 at 15:51
Edited: dpb on 22 Nov 2025 at 16:03
You've got to get the sampling rate from somewhere -- if it isn't in the data file, then you'll have to know it from some other source.
For exposition here, let's assume your data were taken at 500 Hz...
%Read the ECG file in
tECG=readtable("C:\Users\NAME\Documents\ECG_40.txt"); % let's use t for table, and what the data is as variable name
tECG.Properties.VariableNames={'ECG'}; % give the variable a meaningful name, too...
Fs=500; % Sample rate, Hz -- use what is correct for your data
dt=1/Fs; % time sampling interval --> 1/Rate, sec
N=height(tECG); % how many samples there are...
T=(N-1)*dt*1000; % end trace time, msec
tECG=addvars(tECG,linspace(0,T,N).', ...
'NewVariableNames','Time','Before','ECG'); % add the time variable to table
plot(tECG.Time,tECG.ECG) % now plot the trace vs time
title('ECG Plot')
xlabel('Time/ms')
ylabel('Voltage/mV')
grid on
%Show R Peaks
[pks, locs] = findpeaks(tECG.ECG, Fs,'MinPeakHeight', 400); % give it the sampling rate so knows where are
hold on;
plot(locs, pks, 'x'); % add 'x' markers at peak positions
should be close barring typos and the inadvertent slipup...remember to use the correct sampling rate for your actual data...

Community Treasure Hunt

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

Start Hunting!