ggplot 在 for 循环中从数据框中提取行,显示不同的颜色

ggplot with extracting rows from data frame in for loop, showing different colors

我有一个包含每月时间序列数据(从 2010 年 1 月到 2012 年 12 月)的数据框。

    df<- data.frame(code=NA,Year=NA,Month=rep(seq(as.Date('2010/1/1'),by='month',length.out=36),3),x1=rnorm(3*36))
    df$code[1:36]<-1; df$code[37:72]<-2; df$code[73:108]<-3
    yr <- c(rep(2010,12),rep(2011,12),rep(2012,12))
    df$Year<-rep(yr,3)

我想提取具有相同代码的行(每个代码将有 36 行),并将每个代码的值绘制在彼此之上。我尝试通过以下代码实现此目的:

    m <- ggplot(df[1:36,], aes(x=Month,y=x1)) + geom_point() + geom_line(aes(color ='ID:1')) + 
    scale_x_date(labels = date_formatv(format = "%m"),breaks = date_breaks("month"))+ 
    xlab("") + ylab("")+ facet_wrap(~Year,scales=("free_x"))

现在我写了一个 for 循环来提取接下来的 36 个观察结果并将它们添加到绘图中:

    for(i in 1:2){
      data2 <- df[((i*36)+1):((i+1)*36),]
      m<-m+geom_point(data=data2,aes(x=Month,y=x1))+geom_line(data=data2,aes(x=Month,y=x1
                                                                               ,color=paste0('ID:',i+1)))
   }

此代码生成以下图:

现在我的问题是:

(1) 如您所见,我没有得到 ID:2 的图例(它只生成最后一个的图例),我怎样才能得到它?

(2) 我想为每个代码(与图例相关联)看到不同的颜色,我该如何实现?

(3) 我确信应该有更好的方法来产生所需的输出,而不是使用不推荐的 for 循环,有什么建议吗?

code 映射到 color 到您的 aes 语句。

m <- ggplot(df, aes(x=Month,y=x1,color=factor(code))) + 
  geom_point() + 
  geom_line() + 
  scale_x_date(labels = date_format(format = "%m"),breaks = date_breaks("month"))+ 
  xlab("") + ylab("")+ facet_wrap(~Year,scales=("free_x"))
m

不使用 for 循环或子集,而是将 color = factor(code) 添加到您的美学中,这将为每组 36 个添加单独的彩色线条(和点):

m <- ggplot(df, aes(x=Month, y=x1, color = factor(code))) +
    geom_point() + geom_line() + 
    scale_x_date(labels = date_format(format = "%m"),breaks = date_breaks("month"))+ 
    xlab("") + ylab("")+ facet_wrap(~Year,scales=("free_x"))

print(m)

(您自然可以使用 labs(color = "ID") 自定义标签标题,或使用 scale_color_manual 自定义颜色选择)。