Add variable geom_hline to all facets of a barplot

后端 未结 2 724
悲&欢浪女
悲&欢浪女 2021-01-28 07:16

I have a barplot using the ggplot2 library:

plot <- qplot(Date, data=cns, 
              geom=\"bar\", binwidth = 1, 
              fill=Type, facets = N         


        
2条回答
  •  没有蜡笔的小新
    2021-01-28 07:50

    A variant on Didzis's answer, I would make a separate data frame for the summary data that you want to display per facet.

    library("plyr")
    cns.annotate <- ddply(cns, .(Name), summarize, y.int=mean(Days[Type=="Completed"]))
    

    then pass this data frame to geom_hline.

    qplot(Date, data=cns, 
          geom="bar", binwidth = 1, 
          fill=Type, facets = Name ~ .) +
      geom_hline(data=cns.annotate, aes(yintercept=y.int))
    

    or in ggplot rather than qplot syntax:

    ggplot(cns, aes(x=Date)) +
      geom_bar(aes(fill=Type), binwidth=1) +
      geom_hline(data=cns.annotate, aes(yintercept=y.int)) +
      facet_grid(Name ~ .)
    

提交回复
热议问题