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
CodePudding user response:
Not sure I fully understand the question, but here is one possible solution to what I think you are asking.
library(tidyverse)
library(gt)
df <-
data.frame(Concentration = rnorm(30),
Sample = rep(c("A", "B"), 15),
Date = seq.Date(as.Date("2020-01-01"),
as.Date("2020-01-30"), "days"))
interpolated_df <-
df %>%
arrange(Sample) %>%
complete(Sample, Date) %>%
## interpolated is average of value right before and right after
mutate(Interpolations = (lead(Concentration)
lag(Concentration))/2 ) %>%
mutate(Final = coalesce(Concentration, Interpolations))
## plot
interpolated_df %>%
ggplot(aes(x = Date, y = Sample))
geom_tile(aes(fill = Final))
xlab("Day")
ylab("Sample")
Created on 2021-10-25 by the reprex package (v2.0.1)
CodePudding user response:
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)