【问题标题】:Adding main titles from list to graphs in for loop将列表中的主要标题添加到 for 循环中的图形
【发布时间】:2018-12-11 09:28:15
【问题描述】:

我有两个数据集。一个测量了几天的浓度,另一个测量了每个相关日期的风向。

library(ggplot2)

concentrations = data.frame(
  datehour = c("2017-02-15 09:00:00", "2017-02-15 10:00:00","2017-02-15 
               11:00:00", "2017-02-16 09:00:00", "2017-02-16 10:00:00", 
               "2017-02-16 11:00:00"),
  Number = c(3000, 4000, 2000, 6000, 7000, 5000),
  Hour = c(9, 10, 11, 9, 10, 11))

winddir = data.frame(
  Date = c("2017-02-15", "2017-02-16"),
  Wind = c("S", "SW"))

我使用一个 for 循环来创建一个包含每天图表的 PDF。这工作正常。

但是,我想为每个图表添加一个主标题,包括相关日期的日期和风向。因此,我将风向数据框转换为两个列表,以在 for 循环中使用。

我可以很好地使用日期列表,但我不知道如何获取主标题的风向。

我尝试从c = 1 开始,然后将每个循环1 额外添加到c 并使用它从带有paste(wind_list[c]) 的wind_list 中获取项目。这将返回带有 c 数的标题(例如“Wind: 1”、“Wind: 2”等),而不是风向。

#creating the lists
wind_list <- as.list(winddir$Wind)
date_list <- as.list(winddir$Date)

#function for plotting graph
plotdays <- function(){
  ggplot() +
    geom_line(data = concTemp, aes(x = Hour, y = Number))+
                ylab("UFP concentration") + xlab("Hour") + 
    ggtitle(paste("Average UFP concentration per hour on", paste(i),
                  "     Wind:", paste(wind_list[c])))
} 

#the for loop for creating the graphs in 1 PDF

pdf("Test.pdf", onefile = TRUE)
c = 1

for (i in date_list){
  concTemp <- subset(concentrations, grepl(i, datehour))
  if (c == 1){
    wind <-  wind_list[c]
    plotD <- plotdays()
    print(plotD)
    c = c+1
  } else {
    wind <-  wind_list[c]
    plotD <- plotdays()
    print(plotD)
    break
  }
}

dev.off()

有什么建议吗?

【问题讨论】:

  • 我会将风向作为新列添加到浓度数据框中。然后你就有每一行的日期时间和风向,你可以轻松地循环它。

标签: r list for-loop ggplot2


【解决方案1】:

您的包含因子的风表和您的函数似乎读取了基础整数。您可以将风向添加为字符。

#creating the lists
wind_list <- as.list(as.character(winddir$Wind))
date_list <- as.list(as.character(winddir$Date))

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 2015-01-25
    • 2015-11-28
    • 2016-06-21
    相关资源
    最近更新 更多