How to plot average curve out of many curves and showing standard deviation?
Show older comments
Hi everyone, I have many sets of data, each of which has two variables x and y. But the number of data point of each set varies. Now I want to plot an continuous average curve of all curves with showing standard deviation corresponding to each data point (or the overall curve). Two sets are attached here.. Appreciate your help!
Answers (1)
Walter Roberson
on 25 Sep 2017
projectdir = '.';
dinfo = dir( fullfile(projectdir, 'F-d*.txt') );
nfile = length(dinfo);
datatables = cell(nfile, 1);
for K = 1 : nfile
thisfile = fullfile(projectdir, dinfo(K).name);
thistable = readtable(thisfile);
datatables{K} = sortrows( table2timetable(thistable(:,2), 'RowTimes', seconds(thistable.Indentation) ) );
end
synch = synchronize(datatables{:}, 'commonrange', 'linear'); %bring them all into common time base and interpolate
x = seconds(synch.Time);
all_y = synch{:,1:end};
mean_y = nanmean(all_y, 2);
y_std = nanstd(all_y, 0, 2);
plot(x, mean_y, 'b', x, mean_y + y_std, 'r',x, mean_y - y_std, 'g');
legend({'mean curve', 'mean + std', 'mean - std'})
For the pair of sample files, all of the curves are the same location, as the standard deviation is about 1E-9 when the mean is about 1E-6, so +/- the standard deviation is the same to within plotting precision.
The above code uses as data points only the range of x that are in common to all of the data sets -- so 0 to the smallest finish x. If you want to include all of the x with extrapolation for the sections that have no data points, then change the 'commonrange' to 'union'
Note: the final point of F-d_T_28.txt has an x coordinate before the x coordinate of the point before it. That is why I added the sortrows()
Categories
Find more on Time Series Events in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!