简体   繁体   中英

Difference between two lines ggplot2

I wanted to add the difference between two lines to a ggplot2 . In this example, between the lines of the two groups defined by x2 . How can this be done?

y=rbinom(100,1,.4)
x1=rnorm(100, 3, 2)
x2=rbinom(100, 1, .7) 
sub = data.frame(y=y, x1=x1, x2=x2)

ggplot(sub, aes(x1, y, color = x2))   + 
      stat_smooth(method = "glm", family = binomial, formula = y ~ poly(x1,3))

There are two things you should change in your code. First, inside stat_smooth() use x and y and not the actual variable names (function will know that your x values are x1 ). Second, wrap x2 inside factor() to have two distinct colors.

ggplot(sub, aes(x=x1, y=y, color = factor(x2))) + 
  stat_smooth(method = "glm", family = binomial, formula = y ~ poly(x,3))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM