How to add Supplement type type into the ggplot

2019-08-02 13:26发布

I was wondering how I can add the information of each line into the Plot, For example, dashed line in red color refers to 90%CI for male twodash line in green color refers to 90%CI for female longdash line in black color refers to 90%CI for all population

ggplot(mtcars, aes(mpg, disp)) + 
      geom_point(aes(colour=factor(vs), 
      fill = factor(vs)), shape=21, size = 4) + 
      scale_fill_manual(values=c("blue", "pink")) + 
      scale_colour_manual(values=c("black", "black"))+
      geom_hline(yintercept=200, linetype="dashed", color = "darkred")+
      geom_hline(yintercept=250, linetype="dashed", color = "darkred")+
      geom_hline(yintercept=210, linetype="twodash", color = "green")+
      geom_hline(yintercept=215, linetype="twodash", color = "green")+
      geom_hline(yintercept=279, linetype="longdash", color = "black")+
      geom_hline(yintercept=280, linetype="longdash", color = "black")

标签: r ggplot2
1条回答
放荡不羁爱自由
2楼-- · 2019-08-02 14:23

The advice from Axeman is apt. Build a data.frame with the wanted yintercepts and a factor for the grouping of the lines. A single call to geom_hline will the needed aes will generate the plot and a meaningful legend.

library(ggplot2)

lt <- data.frame(yint = c(200, 250, 210, 215, 279, 280),
                 grp  = factor(c(1, 1, 2, 2, 3, 3),
                               levels = 1:3,
                               labels = c("Group 1", "Group 2", "Group 3")))


ggplot(mtcars, aes(mpg, disp)) + 
      geom_point(aes(colour=factor(vs), 
      fill = factor(vs)), shape=21, size = 4) + 
      scale_fill_manual(values=c("blue", "pink")) + 
      scale_colour_manual(values=c("black", "black"))+
      geom_hline(data = lt,
                 mapping = aes(yintercept = yint, linetype = grp))

enter image description here

查看更多
登录 后发表回答