Search code examples
rggplot2raster

How can I interpolate the value of points placed on a timeline?


I want to create an interpolated plot of the concentration of 'x' over time at different locations. If possible, I would like to interpolate the points horizontally (i.e. over time) in a way that I get smooth color-changing horizontal lines for each sample.

df<-data.frame(Concentration = rnorm(30), Position = rep(c(0, 1), 15), Sample = rep(c("A", "B"), 15), Date = seq.Date(as.Date("2020-01-01"), as.Date("2020-01-30"), "days"))

df %>% 
  ggplot(aes(x = Date, y = Position)) +
    geom_hline(yintercept = c(0,1),
              size = 0.3) +
    geom_tile(aes(fill = Concentration),
               interpolate = T) +
    xlab("Day")+
    ylab("Sample")

I would appreciate any suggestions. Lee


Solution

  • That's exactly what ggforce::geom_link was made for.

    library(tidyverse)
    library(ggforce)
    
    set.seed(42)
    df <- data.frame(Concentration = rnorm(30), Position = rep(c(0, 1), 15), Sample = rep(c("A", "B"), 15), Date = seq.Date(as.Date("2020-01-01"), as.Date("2020-01-30"), "days"))
    
    df %>%
      ggplot(aes(x = Date, y = Position)) +
      geom_link2(aes(group = Position, color = Concentration), size = 10) +
      labs(x = "Day", y = "Sample")
    

    Created on 2021-10-25 by the reprex package (v2.0.1)