Here is one way to do it - I use a graphics script for drawing, but the logic for computing the mean and responding to row-state changes is done outside of the drawing.
Working: with data table exclude changes and adding or removing of data filters.
Needs work: (1) Data table and Y column are hard-coded. (2) It only works on the most recent report launched from the script. You can't run it multiple times, or use Redo Analysis to create a second working copy of the report.
NamesDefaultToHere(1);
dt=Open("$SAMPLE_DATA/Big Class.jmp");
gb=dt<<Graph Builder(
Size( 534, 454 ),
Show Control Panel( 0 ),
Variables( X( :height ), Y( :weight ) ),
Elements( Points( X, Y, Legend( 2 ) ) )
);
rpt=(gb<<Report);
// add or update a mean line that honors exclude flags
updateMeanLine=Function({},
rpt[FrameBox(1)] << Remove Graphics Script(1);
rs = rpt[FrameBox(1)] << Get Row States;
val = dt:weight << Get Values;
inc = Loc(1-(rs&2));
m = mean(val[inc]);
Eval(EvalExpr( rpt[FrameBox(1)] << Add Graphics Script(
Pen Color("red");
Y Function(Expr(m), x);
Text Color("red");
Text({X Origin(), Expr(m)}, "Mean=" || Char(Expr(m)));
)));
);
// listen for row-state changes to dt or data filter
rsupdate = Function( {a},
If( Is Matrix( a ),
// row states have changed
updateMeanLine(),
// else (a==-1) indicates that filter may have been added or removed
rsh = rpt[FrameBox(1)] << Make Row State Handler( dt, rsupdate );
)
);
rsh = rpt[FrameBox(1)] << Make Row State Handler( dt, rsupdate );
updateMeanLine();