0

I've created a scatterplot of the relationship between variables x and y1, but I also want to add a fitted line showcasing the relationship between variables x and y2 on the same graph.

I decided to combine the data to make it easier, as follows:

data1 <- data %>% 
  group_by(var) %>% 
  summarize(x = n(), y1 = mean(y1_var), y2 = mean(y2_var))

I hope this isn't too confusing. I don't know how to actually make the plot. I've been trying anything, with my latest attempt being:

data1 %>% 
  ggplot(aes(x = x, y = y1)) + 
  geom_point(color = "blue") + 
  geom_point(x = x, y = y2, color = "yellow") + 
  geom_smooth(method = "lm", se = FALSE)

I know I don't have a good understanding of ggplot2, but just to show sort of where I'm at.

Any help would be appreciated!

stefan
  • 90,330
  • 6
  • 25
  • 51
skarbietae
  • 29
  • 3
  • It would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. If you want to post your data type `dput(data1)` into the console and copy the output starting with `structure(....` into your post. If your dataset has a lot of observations you could do e.g. `dput(head(NAME_OF_DATASET, 10))` for the first ten rows of data. – stefan Apr 01 '22 at 06:16

1 Answers1

0

Not knowing how your data looks like, it is slightly confusing when you state y1 = mean(y1_var). So is y1 just the one mean value? How is that a scatter point?

y1 <- (1:100) + rnorm(100, mean = 1, sd = 1)
y2 <- (100:1) + rnorm(100, mean = 1, sd = 1)
x <- 1:100
df <- data.frame(x, y1, y2)

df %>% 
  ggplot(aes(x = x, y = y1)) + 
  geom_point(colour = "blue") +
  geom_point(aes(x = x, y = y2), colour = "yellow") +
  geom_smooth(aes(x = x, y = y2), method = "lm", se = FALSE)

I've created what it sounds like you're describing. Strange_plot

Godrim
  • 449
  • 2
  • 10