【问题标题】:How to plot a list with multiple data frames in one graph using ggplot in R如何使用 R 中的 ggplot 在一个图中绘制具有多个数据框的列表
【发布时间】:2021-06-30 10:31:30
【问题描述】:

在下面的列表中,有几个数据框表示某个变量的时间序列:

list.data <- list(data.frame(x=c(1:10), y=rnorm(10)),data.frame(x=c(11:20), y=rnorm(10)))

如何使用ggplot 通过循环将这些时间序列绘制在一个图表中,而无需手动输入。 当我尝试使用lapply 时,每个时间序列都绘制在不同的图表中。

lapply(list.data, function(z){ggplot()+geom_line(data=z, aes(x, y))})

手动绘图很乏味,因为我的列表中有很多项目

ggplot()+geom_line(data=list.data[[1]], aes(x, y))+
         geom_line(data=list.data[[2]], aes(x, y), col='red')

有没有不重复geom_line多次的简单方法来绘图

【问题讨论】:

    标签: r list dataframe ggplot2 plot


    【解决方案1】:

    您可以添加列表到ggplot()

    library(ggplot2)
    ggplot() + 
      lapply(list.data, function(z) geom_line(data = z, aes(x, y)))
    


    给定 OP 的示例数据,我们可以先rbind 数据,然后绘制

    ggplot(data = do.call(rbind, list.data)) + 
      geom_line(aes(x, y))
    

    数据

    set.seed(42)
    list.data <- list(data.frame(x=c(1:10), y=rnorm(10)),data.frame(x=c(11:20), y=rnorm(10)))
    

    【讨论】:

      【解决方案2】:

      使用pivot_longer 或zoo 包中的fortify 转换数据。

      【讨论】:

        猜你喜欢
        • 2014-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 2018-11-06
        • 1970-01-01
        • 2014-12-27
        • 2021-07-25
        相关资源
        最近更新 更多