2
$\begingroup$

I'm trying to visually recreate the idea of RSquared between data model from linear regression and my idea was to use ListPlot with data points and model evaluated on the x values of data points and adding the Filling option {1->{2}} keeping in mind that the points in each dataset were sharing the same x coordinates. But the result is not every point filling with its counterpart.

data = List @@@ Table[x -> x + RandomVariate[NormalDistribution[]], {x, RandomReal[{0, 5}, 40]}];
lm = LinearModelFit[data, x, x];
ListPlot[{data, Map[{#, lm[#]} &, data[[All, 1]]]}, Joined -> {False, True}, Filling -> {1 -> {2}}, PlotRange -> All]

Not every point shows the filling

Even without the Joined option not all the points shows the filling between the two datasets. Could be this a Mathematica bug? I'm using Mathematica 12.2.0.0 on macOS 11.5.2 Big Sur.

$\endgroup$
2
  • $\begingroup$ Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) take the introductory tour now, 2) when you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. $\endgroup$
    – bbgodfrey
    Sep 7, 2021 at 15:36
  • $\begingroup$ The bugs tag is reserved for questions where the problem has been vetted by this community and the observed behavior is confirmed to be a bug. Please do not use this tag for new questions. $\endgroup$
    – creidhne
    Sep 7, 2021 at 17:32

1 Answer 1

4
$\begingroup$
SeedRandom[1]
data = List @@@ 
   Table[x -> x + RandomVariate[NormalDistribution[]], {x, RandomReal[{0, 5}, 40]}];

lm = LinearModelFit[data, x, x];

Sort both data sets by x-coordinates:

ListPlot[SortBy[First] /@ {data, Map[{#, lm[#]} &, data[[All, 1]]]},
  Joined -> {False, True}, Filling -> {1 -> {2}}, PlotRange -> All]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.