zucchini
zucchini

Reputation: 33

Can't add a regression line

I'm new to r and trying to run a scatterplot with an added regression line and ID mapped to colour. I've tried :

ggplot(MeanData, aes(x = MeanDifference, y = d, col = ID)) + geom_jitter()+ geom_smooth(method = "lm", se = FALSE) + theme_classic()

however no regression line will appear when I run it.

Another thing I've tried is ggscatter, which I can get to run with a regression line, but I can't figure out how to map ID to colour in that code.

ggscatter(MeanData, x = "MeanDifference", y = "d", add = "reg.line", conf.int = TRUE, cor.coef = TRUE, cor.method = "pearson", xlab = "Mean Difference (degrees)", ylab = "Effect Size (d)")

Can anyone suggest how to run a scatter plot which includes both a regression line and mapping a variable to colour? Thanks in advance!

Upvotes: 0

Views: 246

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145765

The geom_smooth layer will inherit the color aesthetic from the original ggplot() call and try to fit a line for each color - presumably with your data, one line per point. Instead, you need to either (a) specify aes(color = ID) in the geom_jitter layer, not the original ggplot call, or (b) put aes(group = 1) inside geom_smooth so it knows to group all the points together. Either of these should work:

# a
ggplot(MeanData, aes(x = MeanDifference, y = d)) +
  geom_jitter(aes(color = ID)) +
  geom_smooth(method = "lm", se = FALSE) + 
  theme_classic()

# b
ggplot(MeanData, aes(x = MeanDifference, y = d, color = ID)) +
  geom_jitter() +
  geom_smooth(aes(group = 1), method = "lm", se = FALSE) + 
  theme_classic()

Upvotes: 2

Related Questions