Search code examples
plotgraphlinear-regressionoctaveleast-squares

Plot least squares method


So this is my octave plot of a regression line using the least squares method. enter image description here

is there a way to add like little arrows or lines that connect the dots with the actual line? Here is an example of how i want it to look like. Thanksenter image description here


Solution

  • I don't think there's a specific function for plotting residuals, but doing it manually is fairly straightforward:

    % Let's assume this is our model, predicting y from x
      model = @sin;
    
    % Define the x domain, which will be used for plotting
      xdomain = 0:0.1:10;
    
    % Define some (x,y) input points
      xpoints = 10 * rand(1, 10);
      ypoints = model(xpoints) + 0.5 * randn(size(xpoints));
    
    % Plot model
      plot( xdomain, model(xdomain), 'k-', 'linewidth', 1.5 );
      hold on;
    
    % Plot input points
      plot( xpoints, ypoints, 'ko', 'markersize', 8, 'markeredgecolor', 'k', 'markerfacecolor', [0.4,0.4,0.4], 'linewidth', 1.5 )
    
    % Plot residual lines
      plot( [xpoints;xpoints], [model(xpoints);ypoints], 'k:', 'linewidth', 1.5 )
      hold off;