ggplot2如何在单个构面上叠加标记?

时间:2018-10-11 01:41:46

标签: r ggplot2

我想用geom_line()构面创建一个ggplot,但是我希望某些构面在数据上叠加标记。当前代码示例:

sig.1 <- c(rep(c(rep(0,9),2,4,7,10,7,4,2),3),rep(0,7))
sig.2 <- c(rep(c(rep(0,12),10,rep(0,3)),3),rep(0,7))
sig.2.markers <- sig.2*1.2
sig.2.markers[which(sig.2 == 0)] <- NA

df <- data.frame(time=seq(1, length(sig.1)), sig.1, sig.2, sig.2.markers)

df.melt <- melt(df,id='time',variable.name='signal')

# goal: graph with two facets
ggplot(df.melt, aes(x=time, y=value, colour=factor(signal))) + 
    facet_wrap(~signal, ncol=1) +
    scale_color_manual(values=c('blue','black','red')) +
   theme(legend.position = 'none')+
    geom_line()

# facet 2 should look like this with markers superimposed 
ggplot(df, aes(x=time, y=sig.2)) + geom_line() +
        geom_point(aes(x=time, y=sig.2.markers), shape=25, fill="red", size=5, na.rm=TRUE)

输出:

facet graph

但是我希望第二个方面像这样叠加标记(即sig.2.markers):

facet markers

所以总共只有两个方面。任何帮助表示赞赏!谢谢。

1 个答案:

答案 0 :(得分:4)

您可以为任何data =指定不同的geom_参数,因此一种常用的方法是让_line geom获取所有数据,然后制作单独的数据_point几何的框架具有必要的构面列,并且仅填充一个构面:

library(reshape2)
library(ggplot2)

sig.1 <- c(rep(c(rep(0,9),2,4,7,10,7,4,2),3),rep(0,7))
sig.2 <- c(rep(c(rep(0,12),10,rep(0,3)),3),rep(0,7))

sig.2.markers <- sig.2*1.2
sig.2.markers[which(sig.2 == 0)] <- NA

df <- data.frame(time=seq(1, length(sig.1)), sig.1, sig.2)

df.melt <- melt(df, id='time', variable.name='signal')

ggplot() + 
  geom_line(
    data = df.melt, 
    aes(x=time, y=value, colour=factor(signal))
  ) +
  geom_point(
    data = data.frame(
      time = which(!is.na(sig.2.markers)),
      sig.2.markers = sig.2.markers[which(!is.na(sig.2.markers))],
      signal = "sig.2"
    ),
    aes(time, sig.2.markers), shape=25, fill="red", size=5, na.rm=TRUE
  ) +
  facet_wrap(~signal, ncol=1) +
  scale_color_manual(values=c('blue','black','red')) +
  theme(legend.position = 'none')

enter image description here