0

Imagine if my linear regression model was: lm(y~x + N * P) -> (the multiplication is for an interaction)

How would I plot this using ggplot? That all variables are used in the linear regression model. Do I need to use geom_smooth? eventhough the formula in geom_smooth is formula = y~x? does this include the extra variables plus interaction?

I tried:

ggplot(aes(x = x, y = y, color = N) + 
geom_point() + geom_smooth(method = 'lm', formula = 'y~x', fullrange = TRUE)

But I have a feeling it does not add all the variables in my ggplot.

5
  • 2
    To plot regression models with multiple variables I would suggest to estimate you model outside of ggplot and afterwards plot the results via a geom_line, i.e. multiple lines for each or for your desired levels of the interaction terms. See e.g. Add a multivariate linear regression line on a ggplot using R for an example of this approach.
    – stefan
    Commented Mar 26, 2023 at 19:25
  • 1
    The formulay ~ x finds the best fitting line on a plot of y against x, ignoring your other two variables. If we add a second independent variable by using the formula y ~ x + N then conceptually we are finding the best fitting plane through a cloud of points in a 3D space with y, x and N on 3 orthogonal axes. This would have to be shown as a 3D plot, or as several lines that are "slices" through this plane. The formula y ~ x + N * P represents the best fitting 3D space through a 4D point cloud and is very hard to represent on a 2D plot, though using 2 faceting dimensions might work Commented Mar 26, 2023 at 19:51
  • 2
    Without seeing your data or understanding what you are trying to illustrate with your plot, we can't really give you any more definite advice. Perhaps you could edit your question to include reproducible data? Thanks. Commented Mar 26, 2023 at 19:53
  • I think this should probably be closed as a duplicate of the Q linked by @stefan, but maybe the OP could confirm ...
    – Ben Bolker
    Commented Mar 26, 2023 at 20:05
  • Please provide enough code so others can better understand or reproduce the problem.
    – Community Bot
    Commented Mar 27, 2023 at 13:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.