-1

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?

Hallie Sheikh
  • 381
  • 3
  • 12

2 Answers2

3

You have two options.

First: your data.

datalu <- tibble::tribble(
         ~V1, ~Lon, ~Lat, ~Year, ~UB,   ~CA,   ~PR, ~FO, ~`NA`,
    13258323,   61, 29.5,  1750,   0, 0.009, 0.087,   0, 0.982,
    13258324,   61, 29.5,  1751,   0, 0.009, 0.088,   0, 0.982,
    13258325,   61, 29.5,  1752,   0, 0.009, 0.078,   0, 0.571,
    13258326,   61, 29.5,  1753,   0, 0.009, 0.068,   0, 0.471
)

In this graph you select manually each variable and with scale_colour_manual you can choose the colours you want.

library(ggplot2)

ggplot(datalu, aes(x = Year)) +
    geom_line(aes(y = CA  , colour = "CA"), size = 1) +
    geom_line(aes(y = PR  , colour = "PR"), size = 1) +
    geom_line(aes(y = `NA`, colour = "NA"), size = 1) +
    scale_color_manual(values = scales::hue_pal()(3)) +
    theme_light() +
    labs(y = "Value",
         colour = "Series")


enter image description here

With this one you use a little trick: you gather your data in long form with gather and it automatically select colours for you.

I selected the columns because I wasn't sure how your full data look like.

library(ggplot2)
library(dplyr)
library(tidyr)

datalu %>%
    select(CA, PR, `NA`, Year) %>% 
    gather(series, value, -Year) %>% 
    ggplot(aes(x = Year, y = value, colour = series)) +
    geom_line(size = 1) +
    theme_light()
    

enter image description here

Edo
  • 7,567
  • 2
  • 9
  • 19
2

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)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87