sassgplot

How to adjust the range of the regression line in SAS proc sgplot


The SAS code for the data and plot is below. The regression line will be determined by the 10 data point I have, but I want to control the start and the end of the regression line. For example, I want to keep my current plot, the only change is that I want the regression line begin at day=3 and end at day=8. Now the regression line begin at day=1 and end at day=10. How can I do it?

data my_data;
    input day sales;
    datalines;
1 7
2 12
3 15
4 14
5 13
6 11
7 10
8 16
9 18
10 24
;
run;

proc sgplot data=my_data;
    reg x=day y=sales;
     xaxis min=0 max = 12 values=(0 to 12 by 1);
     yaxis min=0 max = 25 values=(0 to 25 by 1);
run;


Solution

  • You will have to capture the computed regression line coefficients from Proc REG output and add the endpoints of your desired line segment as rows to the data to be plotted with a SERIES statement.

    Since you are going to essentially hide the SGPLOT REG line you can plot the data points with just SCATTER

    Example:

    The REG statement is used for instructive purposes and to show the computed line segment from Proc REG does align with the line computed for REG statement. The SERIES line was thickened for instructive purposes.

    data have;
        input day sales;
        datalines;
    1 7
    2 12
    3 15
    4 14
    5 13
    6 11
    7 10
    8 16
    9 18
    10 24
    ;
    run;
    
    ods html file='reg.html';
    
    ods exclude all;
    ods output ParameterEstimates=PE;
    proc reg data=have;
       model sales = day;
    run;
    ods exclude none;
    proc transpose data=PE prefix=coeff_ out=coeff(keep=coeff_:);
      var estimate;
      id variable;
    run;
    
    data line;
      set coeff;
      day = 3; sales_y = coeff_intercept + coeff_day * day; output;
      day = 8; sales_y = coeff_intercept + coeff_day * day; output;
      keep day sales_y;
      label sales_y = 'sales';
    run;
    
    data plotdata;
      set have line;
    run;
    
    
    proc sgplot data=plotdata noautolegend;
      * scatter x=day y=sales;
    
        reg x=day y=sales;
    
        series x=day y=sales_y / lineattrs=(thickness=12);
    
        xaxis min=0 max=12 values=(0 to 12 by 2)  minor minorcount=1;
        yaxis min=0 max=25 values=(0 to 25 by 5)  minor minorcount=4;
    
    run;
    ods html close;
    

    enter image description here