如何使geom_abline show_guide线条类型正确显示在图例中

时间:2015-08-10 17:28:17

标签: r ggplot2

set.seed(586)
data<-data.frame(x=sort(runif(20)),y=sort((rnorm(1)*1:20*.234)),grp=factor(sample(c(0,1),20,replace = T)))

ggplot(data, aes(x=x, y=y, shape=grp)) + 
  geom_point() +
  theme_classic() +
  scale_shape_manual("PT Status",
                     values=c(1,3),
                     breaks=c(0,1),
                     labels=c("No","Yes"))+
  scale_x_continuous("My x") +
  scale_y_continuous("My y")+
  geom_abline(intercept=.12, slope=.98,linetype=1,show_guide = TRUE)+     
  geom_abline(intercept=.05, slope=(-.3+.98),linetype=3,show_guide = TRUE)+
 theme(legend.position="bottom")

enter image description here

线条看起来正确,我喜欢线条如何整合到图例中。但显然在我的代码中我没有指定哪些数据去哪个abline。是否有一种方法可以在geom_abline代码中简单地指出这一点,或者以其他方式对其进行重新编码以使第一个是实体而第二个是虚线的,就传奇而言?

使用@Jorans建议我创建了

smDf<-data.frame(intercept=c(.12,.05),slope=c(.98, (-.3+.98)),linetype=factor(c(1,3)))

然后新代码是:

ggplot(data, aes(x=x, y=y, shape=grp)) + 
  geom_point() +
  theme_classic() +
  scale_shape_manual("PT Status",
                     values=c(1,3),
                     breaks=c(0,1),
                     labels=c("No","Yes"))+
  scale_x_continuous("My x") +
  scale_y_continuous("My y")+
  geom_abline(aes(intercept=intercept, slope=slope, linetype=linetype), data=smDf, show_guide = TRUE)

这给了我:

enter image description here

那么现在如何整合这两个?

1 个答案:

答案 0 :(得分:1)

我认为这可以更好地记录,但你基本上需要给出相同基本结构的ggplot手动量表,以便合并它们:

ggplot() + 
    geom_point(data = data,aes(x=x, y=y, shape=grp)) +
    geom_abline(aes(intercept=intercept, slope=slope, linetype=linetype), data=smDf,show_guide = TRUE) +
    theme_classic() +
    scale_shape_manual(name = "PT Status",
                       values=c(1,3),
                       breaks=c(0,1),
                       labels=c("No","Yes"))+
    scale_linetype_manual(name = "PT Status",
                          values=c(1,3),
                          labels=c("No","Yes"))+
    scale_x_continuous("My x") +
    scale_y_continuous("My y")