user3616494
user3616494

Reputation: 63

How to draw straight line cross center of data in scatter plot?

I wanted to draw a scatter plot with ggplot which geom_smooth() cross center of my data with 45 degree angle not drawing automatically.

As it shows here the geom_smooth() has small slop and I changed different method lm, auto and etc, but there was no difference.

geom_smooth(color = "black", alpha = 0.5, method = "lm", se = F)

How can I draw line in way exactly cross middle of the pink dots?

enter image description here

Upvotes: 0

Views: 2246

Answers (3)

David Mas
David Mas

Reputation: 1209

Do you want something like this?

geom_abline(intercept = 0, slope = 1)

This wll draw a line with a 45º angle that goes through 0.

I think geom_smooth is computing the regression fr all the points. Try to remove all color argument to get the smooth by group. You can check the different plots

a <- data.frame(x = c(1:10,2:11),y = c(2:11,1:10), label = c(rep("a",10),rep("b",10)))

ggplot(a, aes(x,y)) + geom_point(aes(color = label)) + geom_smooth(aes(color = label))
ggplot(a, aes(x,y)) + geom_point(aes(color = label)) + geom_smooth(color="black")

Upvotes: 1

Marc in the box
Marc in the box

Reputation: 12005

library(ggplot2)
n <- 300
x <- seq(0,100,,n)
type <- factor(c(0,1)[sample(1:2, n, replace = TRUE)])
y <- 4 + 2*x + rnorm(n, sd=10) - 10*as.numeric(type)
df <- data.frame(x=x, y=y, type=type)
plot(y~x, df, bg=c("blue", "pink")[df$type], pch=21)

bp <- ggplot(df, aes(x = x, y = y, col=type))
bp +
  geom_point() +
  geom_smooth(color = "black", alpha = 0.5, method = "lm", se = F) + 
  geom_smooth(aes(group = type), data = subset(df, type==0), se=F)

enter image description here

Upvotes: 0

Stephen
Stephen

Reputation: 324

geom_smooth(aes(group = type))

This will give a different curve for each type. You can then figure out how to exclude the others if you want

Upvotes: 0

Related Questions