Plotting multiple time series on the same plot using ggplot()

后端 未结 6 1968
北恋
北恋 2020-12-02 07:09

I am fairly new to R and am attempting to plot two time series lines simultaneously (using different colors, of course) making use of ggplot2.

I have 2 data frames.

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 07:31

    An alternative is to bind the dataframes, and assign them the type of variable they represent. This will let you use the full dataset in a tidier way

    library(ggplot2)
    library(dplyr)
    
    df1 <- data.frame(dates = 1:10,Variable = rnorm(mean = 0.5,10))
    df2 <- data.frame(dates = 1:10,Variable = rnorm(mean = -0.5,10))
    
    df3 <- df1 %>%
      mutate(Type = 'a') %>%
      bind_rows(df2 %>%
                  mutate(Type = 'b'))
    
    
    ggplot(df3,aes(y = Variable,x = dates,color = Type)) + 
      geom_line()
    

提交回复
热议问题