仅为1组ggplot添加lm

时间:2016-07-08 15:30:54

标签: r ggplot2

我有下面的情节,我想在情节中添加回归线,仅用于" mu"领域。当我添加geom_smooth时,会添加4个回归线。我只想添加1.是否也可以在图例中添加回归线,并将模型y = b0 + b1x,r ^ 2的文本添加到图中?

这里是代码 - 你可以看到多个回归线:

library(dplyr)
library(tidyr)
library(lattice)
library(ggplot2)
x = c( rep(c(1,2,3,4,5),4)  )
group = c( rep(c(10,10,10,10,10),2),rep(c(20,20,20,20,20),2) )
lbl = paste0(  c("0%", paste0(   unique(group)[1:(length(unique(group))-1)]   ,"%" )  ) 
               ," - ",
               paste0(unique(group),"%"))
lbl
value = rnorm(20)
dat = data.frame( x= x , group  = group, value = value)
dat = dat %>% # create the mu, sd, q1 and q3 aggregates
  group_by(group,x)  %>%  
  summarise(mu =  round(mean(value),2), 
            sd= sqrt(round(sd(value),2)), 
            Q1 = quantile(value)[2],
            Q3 = quantile(value)[4],
            count = n())
dat
dat2 = dat %>%  gather (key = Metric, value= Value,c(mu, sd, Q1, Q3)) #melt the data
as.data.frame(dat2)
ggplot(data=dat2 , aes(x=x, y=Value, group = Metric,colour = Metric,linetype = Metric)) + 
  geom_line()  + geom_point() + ylab("value") + 
  xlab("v") + 
  scale_x_discrete(breaks = c( seq(1,5,1)  ) ) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  scale_y_continuous(breaks = c( seq(-3,3,.25)  )  ) +
  scale_colour_manual(values=c(mu = "blue", sd = "blue", Q1 = "red", Q3 = "red")) +
  scale_linetype_manual(values =c(mu = "dashed", sd= "solid", Q1 = "solid", Q3 = "solid"))  +
  facet_wrap(~ group, scales = "free",ncol=3, labeller = as_labeller(setNames(lbl, sort(unique(group))))) +
  theme(strip.text.x = element_text(size=10, angle=0),
        strip.text.y = element_text(size=12, face="bold"),
        strip.background = element_rect(colour="red", fill="#CCCCFF")) +
  geom_smooth(method=lm,   se=FALSE)  +
  geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)

0 个答案:

没有答案