【问题标题】:Loop over objects in ggplot在ggplot中循环对象
【发布时间】:2021-11-08 06:00:05
【问题描述】:

我有多个相同格式的数据框,我想使用 ggplot 在同一个图表中创建多条曲线。每个数据框都有一年的数据,从 1956 年到 2019 年。例如:

Year1956 <- data.frame(prob=c(5, 10, 20, 30, 100), Qmcs=c(1000, 500, 50, 10, 5))
Year1957 <- data.frame(prob=c(1, 3, 25, 35, 100), Qmcs=c(800, 600, 100, 50, 30))

可以在同一个图表中手动绘制这些多个对象,其中 ... 是 Year1958 到 Year2018

ggplot()+
  geom_line(data=Year1956, aes(x=prob, y=Qmcs))+
  geom_line(data=Year1957, aes(x=prob, y=Qmcs))+
  ...
  geom_line(data=Year2019, aes(x=prob, y=Qmcs))

由于有很多数据帧,有没有办法在循环中执行此操作?提前谢谢你。

【问题讨论】:

    标签: r dataframe loops ggplot2


    【解决方案1】:

    我的回答不是展示如何遍历数据帧列表以生成单独的geom_line,而是展示如何组合类似结构化的 data.frames 并在单个 geom_line 中完成所有操作。

    假设我们有一系列数据帧,其模式为"Year" + number

    library(ggplot2)
    
    Year1956 <- data.frame(prob=c(5, 10, 20, 30, 100), Qmcs=c(1000, 500, 50, 10, 5))
    Year1957 <- data.frame(prob=c(1, 3, 25, 35, 100), Qmcs=c(800, 600, 100, 50, 30))
    

    我们可以通过循环多年来并使用get()函数系统地收集所有满足模式的data.frames。

    years <- c(1956:1957)
    
    mylist <- lapply(setNames(nm = years), function(i) {
      get(paste0("Year", i), mode = "list")
    })
    

    最后,我们可以将所有这些 data.frame 组合在一起,并通过使用 data.table::rbindlist() 中的 idcol 参数来跟踪我们的年份。然后绘制数据将很简单。

    df <- data.table::rbindlist(mylist, idcol = "year")
    df$year <- as.numeric(df$year)
    
    ggplot(df, aes(prob, Qmcs, group = year)) +
      geom_line()
    

    reprex package (v2.0.1) 于 2021-09-12 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 2020-02-17
      • 1970-01-01
      相关资源
      最近更新 更多