Search code examples
rscatter-plot

Scatter plot with dates in R


Could you help me make a scatter plot of the df database?. The x axis would be the dates and the y axis would be the values corresponding to d1 and d2. Also, I would like to put as x-axis caption "date" and y-axis caption "d".

  df <- structure(
      list(date = c("2021-01-01","2021-01-02","2021-01-03","2021-01-04","2021-01-05"),
           d1 = c(0,1,4,5,6), d2 = c(2,4,5,6,7)),class = "data.frame", row.names = c(NA, -5L))

Solution

  • Get the data in long format for the d1 and d2 variables.

    Using ggplot2 here is one way to plot this data -

    library(tidyverse)
    
    df %>%
      pivot_longer(cols = -date) %>%
      mutate(date = as.Date(date)) %>%
      ggplot() + aes(date, value, color = name) + 
      geom_point(size = 2) + 
      labs(x = 'date', y = 'd') + 
      theme_classic()
    

    enter image description here