0

I have an excel file with multiple columns with titles as x, x1, x2, x3, x4 etc. I am using ggplot function in R to plot x against x1. The code is

data %>%
  ggplot(aes(x = x1, y = x)) + 
  geom_point(colour = "red") +
  geom_smooth(method = "lm", fill = NA)   

How to modify the present code so as to plot x against x1, x against x2, x against x3, x against x4 in the same ggplot function code

camille
  • 16,432
  • 18
  • 38
  • 60
  • [This answer](https://stackoverflow.com/a/55632137/6478701) doesn't use ggplot, but solves a similar problem. Maybe it will help you. – RoB May 24 '19 at 12:22
  • Just FYI you were missing an + between the two geoms. I added it back in but wanted to bring it to your attention in case it has anything to do with your issue. Also, it's very hard to help with this without a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). We can't see your data or your current output. – camille May 24 '19 at 16:26

1 Answers1

0

You should change the way your data.frame is formated to do this easily with ggplot2 syntax. Instead of having 5 columns, with x, x1, x2, x3, x4, you may want to have a data.frame with 3 columns : x, y and type with type being a categorical variable indicating from which column your y is from (x1, x2, x3 or x4).

That would be something like this :

df <- data.frame(x = rep(data$x, 4), 
                 y = c(data$x1, data$x2, data$x3, data$x4), 
                 type = rep(c("x1", "x2", "x3", "x4"), each = nrow(data))

Then, with this data.frame, you can set the aes in order to plot x according to y for each category of your variable type thanks to the color argument.

ggplot(df, aes(x = x, y = y, color = type)) + geom_point() + geom_smooth(method = "lm, fill = "NA")

You should check http://www.sthda.com/english/wiki/ggplot2-scatter-plots-quick-start-guide-r-software-and-data-visualization for detailed explanations and customizations.

  • 1
    Depending on the number of columns you have, it may be easier to generalize Chaarti's answer using `colnames(d)[-1]` to get the `x1 x2 x3 ... xn` names. – Slagt May 24 '19 at 13:22
  • 3
    There are almost certainly better ways to reformat this data than by hardcoding a new data frame, such as with `melt`, `gather`, `stack`. But it would be easier to give a good answer if the OP had included a sample of data – camille May 24 '19 at 16:30