【问题标题】:For loop in ggplot for multiple time series vizggplot中的for循环用于多个时间序列,即
【发布时间】:2022-01-15 04:37:23
【问题描述】:

我需要在我的数据集中为每个时间序列(列)制作多个单独的图:

https://github.com/rhozon/datasets/raw/master/multiple_time_series_dataset.csv

我想到了一些循环遍历每一列并单独绘制每个图表的 for 循环。

ggplot(df, aes(x = timestamp, 
               y = for loop for each column) ) +
geom_line()

如何通过为数据集的每一列生成时间图来节省时间?

【问题讨论】:

    标签: r ggplot2 time-series data-visualization gplots


    【解决方案1】:

    也许这就是你要找的东西

    library(tidyverse)
    library(lubridate)
    library(plotly)
    df <- vroom::vroom("https://github.com/rhozon/datasets/raw/master/multiple_time_series_dataset.csv")
    
    df <- df %>% 
      mutate(timestamp = dmy(timestamp))
    
    VARS <- names(df)[-1][1:3]         
    
    map(.x = VARS,
        .f = ~ ggplot(df, aes(x = timestamp, y = .data[[.x]])) +
          geom_line()) %>%
      map(ggplotly)
    

    【讨论】:

    • 很遗憾我没有使用 ggplotly
    • 很棒的@Yuriy Saraykin,但是在这里如何使用ggplotly?
    • 更新解决方案
    【解决方案2】:

    您可以尝试使用 lapply 而不是 for 循环来跟踪代码。

    # transforming timestamp in date object
    df$timestamp <- as.Date(df$timestamp, format = "%d/%m/%Y")
    # create function that is used in lapply
    plotlines <- function(variables){
      ggplot(df, aes(x = timestamp, y = variables)) +
      geom_line() 
    }
    # plot all plots with lapply
    plots <- lapply(df[names(df) != "timestamp"], plotlines) # all colums except timestamp
    plots
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-02
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      相关资源
      最近更新 更多