Search code examples
rggplot2raster

Temporal time series in ggplot with multiple variables


I have a dataframe in R:

datalu
V1 Lon  Lat           Year     UB    CA      PR        FO  NA
1   13258323  61 29.5 1750     0    0.009   0.087      0   0.982
2   13258324  61 29.5 1751     0    0.009   0.088      0   0.982
3   13258325  61 29.5 1752     0    0.009   0.078      0   0.571
4   13258326  61 29.5 1753     0    0.009   0.068      0   0.471

I would like to plot a temporal graph of time series (in form of line) of variables of CA,PR, NA in ggplot in one graph showing different colors. In reality I have many years (100+ years), but just to serve as an example for the dataframe I have mentioned only four years. How can it be achieved in ggplot in R?


Solution

  • It's best to use pivot_longer to reshape your data:

    library(ggplot2)
    library(dplyr)
    
    datalu %>% 
      tidyr::pivot_longer(cols = c("UB", "CA", "PR", "FO", "NA.")) %>%
      ggplot(aes(x = Year, y = value, color = name)) + geom_line()
    

    Created on 2020-08-04 by the reprex package (v0.3.0)