I am trying to add a linear regression to data plotted with ggplot; however, due to the nature of my data I need to plot it such that the responding variable in the linear regression is the x-axis, not the y. Is there a way to change the way the regression is done (I tried changing "formula = y~x" to "formula = x~y" but no luck) by maybe specifying alternate mapping from the mapping specified by the plot? Or is there an easy way to invert the plot after I have added the regression? Thanks! Any help is appreciated.
One straightforward way (which you suggested) would be to make the plot with y
and x
reversed, and then "inverting" the final plot. I used heavily right skewed "noise" so the example really makes it clear what is being fit.
library(tidyverse)
set.seed(42)
foo <- data_frame(x = 1:100, y = 2 + 0.5*x + 3*rchisq(100, 3))
foo %>%
ggplot(aes(x=y, y=x)) + geom_point() + stat_smooth(method = "lm") + coord_flip()