Scatter Plot with best-fit line using StatPlots
Download file: ScatterPlotStatPlot.pg
DOCUMENT();
loadMacros(
'PGstandard.pl', 'PGML.pl',
'StatisticalPlots.pl', 'PGstatisticsmacros.pl',
'PGcourse.pl'
);
Preamble
Make sure that StatisticalPlots.pl is loaded. This is a version of the problem in Scatter Plot that uses the scatter plot feature in StatisticalPlots.pl.
@data = ([ 5, 40 ], [ 7, 120 ], [ 12, 180 ], [ 16, 210 ], [ 20, 240 ]);
$x = [ map { $_->[0] } @data ];
$y = [ map { $_->[1] } @data ];
($m, $b) = linear_regression($x, $y);
$plot = StatPlot(
xmin => 0,
xmax => 24,
xtick_delta => 4,
ymin => 0,
ymax => 300,
ytick_delta => 50,
aria_label => 'Linear Regression'
);
$plot->add_scatterplot(
~~@data,
marks => 'circle',
color => 'blue'
);
$plot->add_function(
"$m x + $b",
'x',
1,
23,
color => 'black',
width => 1,
);
Setup
For this problem, we have a data set stored as an array of array
references. First we find the best-fit line using the
linear_regression function of PGstatisticsmacros.pl.
Note that the x and y data values need to be in array references, and
the 2nd and 3rd lines extract the components.
Set up the StatPlot with a plotting window that will
contain the data. The add_dataset method adds the data to
the plot with circle marks that are colored blue.
The line is added to the dataset with the add_function
method. The 3rd and 4th arguments are the xmin and xmax of the
domain.
BEGIN_PGML
A scatter plot of the data:
[``` [@ join(', ', map { "($_->[0], $_->[1])" } @data) @] ```]
together with the best-fit line is given by the following plot.
>> [! Scatter Plot with best fit line !]{$plot}{500} <<
END_PGML
Statement
To format the points in the @data array in a
human-readable manner, these are first put in “(x, y)” form using the
map function. The resulting array is then concatenated with
the join command. Since both map and join are perl
commands, this compound command is placed within a
[@ @].
The [! !]{}{} is a PGML format for inserting an
image.
BEGIN_PGML_SOLUTION Solution explanation goes here. END_PGML_SOLUTION ENDDOCUMENT();
Solution
A solution should be provided here.