2017-04-18 107 views
0

我有不同组别组件的时间序列数据。带有各种时间戳的每个组ID(作为日期给出)具有低位和高位响应数据。我想通过facet(ggplot)为(1)Group ID和响应(即(2)Hyper和Hypo响应)绘制每个组的时间序列,以便通过响应的图像是另一个的顶部。任何帮助表示赞赏。通过ggplot在R中绘图

下面给出了一个演示数据集和我迄今为止所做的工作。

set.seed(1) 
tdat <- data.frame(Group = rep(paste0("GroupID-", c("A","B")), 
           each = 100), 
        Date = rep(seq(Sys.Date(), by = "1 day", length = 100), 2), 
        Fitted = c(cumsum(rnorm(100)), cumsum(rnorm(100))), 
        Signif = rep(NA, 200)) 
tdat <- transform(tdat, Hyper = Fitted + 1.5, Hypo = Fitted - 1.5) 
## select 1 region per Site as signif 
take <- sample(10:70, 2) 
take[2] <- take[2] + 100 
tdat$Signif[take[1]:(take[1]+25)] <- tdat$Fitted[take[1]:(take[1]+25)] 
tdat$Signif[take[2]:(take[2]+25)] <- tdat$Fitted[take[2]:(take[2]+25)] 

和数据帧是这样的 -

> head(tdat) 
     Group  Date  Fitted Signif  Hyper  Hypo 
1 GroupID-A 2017-04-18 -0.6264538  NA 0.8735462 -2.1264538 
2 GroupID-A 2017-04-19 -0.4428105  NA 1.0571895 -1.9428105 
3 GroupID-A 2017-04-20 -1.2784391  NA 0.2215609 -2.7784391 
4 GroupID-A 2017-04-21 0.3168417  NA 1.8168417 -1.1831583 
5 GroupID-A 2017-04-22 0.6463495  NA 2.1463495 -0.8536505 
6 GroupID-A 2017-04-23 -0.1741189  NA 1.3258811 -1.6741189 

时间序列被日期给出。

我绘制的数据如下。然而,我的真实数据有更多的组ID,我真的很想为每个组ID分配一张图片,将图片分解为Hyper和Hypo响应。

library(ggplot2) 
ggplot(tdat, aes(x = Date, y = Fitted, group = Group)) + 
    geom_line() + 
    geom_line(mapping = aes(y = Hyper), lty = "dashed") + 
    geom_line(mapping = aes(y = Hypo), lty = "dashed") + 
    geom_line(mapping = aes(y = Signif), lwd = 1.3, colour = "red") + 
    facet_wrap(~ Group) 

再次,任何帮助表示赞赏。

感谢

+0

所以在你的榜样的情节是不是你预期的输出?您是否尝试过'facet_grid()'而不是? – Jimbou

回答

3

如何这样的事情,用geom_ribbon展现超和低价值:

tdat %>% 
ggplot(aes(Date, Fitted)) + 
    geom_line(lty = "dashed") + 
    geom_line(aes(y = Signif), lwd = 1.3, color = "red") + 
    geom_ribbon(aes(ymin = Hypo, ymax = Hyper, group = Group), alpha = 0.2) + 
    facet_grid(Group ~ .) + 
    theme_light() 

结果: enter image description here

+0

对不起,下面给出的图片有效。 – user44552

+0

是的,它更好地回答你写的问题。至于哪个更好的可视化,那么你是法官:) – neilfws

5

如果将reshapereshape2tidyr数据或data.table并将宽转换为长:

library(reshape2) 
tdat2<-melt(tdat,id.vars = c("Group","Date","Signif","Fitted")) 

ggplot(tdat2, aes(x = Date, y = value, group = Group)) + 
geom_line() + 
geom_line(mapping = aes(y = Signif), lwd = 1.3, colour = "red") + 
facet_wrap(variable~ Group) 

enter image description here

+0

而不是使用'facet_wrap'我会使用'facet_grid(变量〜组)'。海事组织是更优雅和日历。 – Jimbou

+0

我不想改变任何事情,只是给OP想要的东西。 OP使用'facet_wrap(〜Group)'。同意'facet_grid'可能更干净,'theme'可以改进。 –

+0

这不是批评。只是一个额外的评论。 – Jimbou