How do I plot multiple lines of best fit on a scatter plot?
Show older comments
Hi,
I'm struggling to plot three data series onto a scatter plot, with each series having its own line of best fit (linear). My code is below. My three data series are (x1,y1), (x1,y2) and (x2,y3) with corresponding error bars for each series. When I try plotting the lines, they do not appear correctly and also some points from the first data series do not appear on the graph, but the error bars do. I have tried reordering the code etc but I can't understand what I'm doing wrong here. Any help would be greatly appreciated.
x1 = [20 40 60 80 100] ;
x2 = [20 40 60 80] ;
y1 = [0.240671275 0.552924282 0.874381642 0.99074338 1.354697701] ;
err1 = [0.052548669, 0.08814497, 0.117517615, 0.117123163, 0.167532477] ;
y2 = [0.11101623 0.11247439 0.208469577 0.322969453 0.386224488] ;
err2 = [0.133008916 0.125080979 0.1156091 0.11321253 0.119709187] ;
y3 = [0.111780925 0.162983696 0.31700554 0.378830489] ;
err3 = [0.056024757 0.050835675 0.071003682 0.058800409] ;
figure(1)
xlim([0 105]) ;
scatter(x1,y1, 'g', 'Linewidth', 5)
Fit1 = polyfit(x1,y1,1);
plot(polyval(Fit1,x1));
eb1 = errorbar(x1,y1,err1, 'vertical', 'LineStyle', 'none') ;
set(eb1, 'color', 'k', 'LineWidth', 2);
hold on
scatter(x1,y2, 'r', 'Linewidth', 5)
Fit2 = polyfit(x1,y2,1);
plot(polyval(Fit2,x1));
eb2 = errorbar(x1,y2,err2, 'vertical', 'LineStyle', 'none') ;
set(eb2, 'color', 'k', 'LineWidth', 2)
hold on
scatter(x2,y3, 'b', 'Linewidth', 5)
Fit3 = polyfit(x2,y3,1);
plot(polyval(Fit3,x2));
eb3 = errorbar(x2,y3,err3, 'vertical', 'LineStyle', 'none') ;
set(eb3, 'color', 'k', 'LineWidth', 2);
Accepted Answer
More Answers (1)
dpb
on 17 Oct 2020
All of
Fit1 = polyfit(x1,y1,1);
plot(polyval(Fit1,x1));
should be
Fit1 = polyfit(x1,y1,1);
plot(x1,polyval(Fit1,x1));
You plotted the predicted value versus ordinal number of the observation, not the x vector of interest.
Better would be to compute and save the predicted values and plot them, probably. Then you've got those values for error, etc.
Fit1 = polyfit(x1,y1,1);
yHat1=polyval(Fit1,x1));
hL1=plot(x1,yHat1);
Categories
Find more on Graphics Performance 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!