1

也许是一个简单的问题,但我无法弄清楚。那是我原来的df:

                Date.time      P    ID
    1   2013-07-03 11:15:00 1207.7  K0904
    2   2013-07-03 11:20:00 1207.7  K0904
    3   2013-07-03 11:25:00 1207.9  K0904
    4   2013-07-03 11:30:00 1208.0  K0904
    5   2013-07-03 11:35:00 1208.0  K0904
    ....
    70  2013-07-03 17:00:00 1208.6  K0955
    71  2013-07-03 17:05:00 1208.4  K0955
    72  2013-07-03 17:10:00 1208.4  K0955
    73  2013-07-03 17:15:00 1208.6  K0955
    74  2013-07-03 17:20:00 1208.8  K0955
    ...

并使用此代码

    ggplot(df1, aes(x=Date.time, y=P, group=ID, color=ID)) + 
      geom_line() +
      facet_grid(~ID) +
      theme(legend.position="none")

我创建了这个情节

在此处输入图像描述

只是我想将最后 3 个图覆盖到前 3 个图(因此图更小且更具可读性。我尝试将 df 拆分为 2 个,每个由 3 个 ID 组成,然后将它们组合起来geom_line(),为每个 df 添加 2 个但没有任何改变。有什么想法吗?提取新 df 的代码是:

df1<-subset(df, ID %in% c("K1142", "K0904", "K1136"))
df2<-subset(df, ID %in% c("K0955", "K1148", "K8651"))

然后是新的尝试

ggplot(df1, aes(x=Date.time, y=P, group=ID, color=ID)) + 
  geom_line() +
  geom_line(data=df2, aes(x=Date.time, y=P, color=ID)) +
  facet_grid(~ID) +
  theme(legend.position="none")
4

1 回答 1

5

这将完成这项工作(基本上是@MattParker 建议的)

# Recreate your data (fake)
Date.time <- rep(1:100, 6)
P <- runif(600) + rep(0:5, each=100)
ID <- gl(6, 100, labels=c("K1142", "K0904", "K1136", "K0955", "K1148", "K8651"))
d <- data.frame(Date.time=Date.time, P=P, ID=ID)


#Create a new dummy variable to facet by
#    (There's a cleaner way to do this, but this way is easy to understand)
d$newID <- NA
d$newID[d$ID %in% levels(d$ID)[1:2]] <- "groupA"
d$newID[d$ID %in% levels(d$ID)[3:4]] <- "groupB"
d$newID[d$ID %in% levels(d$ID)[5:6]] <- "groupC"

# Make the plot, faceting on the dummy variable
ggplot(d, aes(x=Date.time, y=P, colour=ID)) + geom_line() +
  facet_wrap(~newID)
于 2013-08-15T20:45:19.310 回答