hkj447
hkj447

Reputation: 737

Shading different regions of the graph based on time period

I am creating a graph using ggplot2 that takes dates on the x-axis (i.e 1000 years ago) and probabilities on the y-axis. I would like to distinguish different time periods by shading regions of the graph different colors. I stored the following dates here:

paleo.dates <- c(c(13500,8000), c(13500,10050) ,c(10050,9015), 
c(9015,8000), c(8000,2500), c(8000,5500), c(5500,3500), c(3500,2500), 
c(2500,1150), c(2500,2000), c(2000,1500), c(1500,1150), c(1150,500))

I would like to take a time period, say 13500 to 8000, and color code it until it overlaps with another date, such as the third entry.

I am using the ggplot2 cheatsheat, and I attempted to use aes(fill = paleo.dates), but this does not work as it is not the same length as my dataset. I was also thinking of using + geom_rect() to manually fill the areas, but that does not seem very elegant, and I am not sure it will even work.

Any advice is appreciated, thank you.

Upvotes: 0

Views: 207

Answers (1)

bbiasi
bbiasi

Reputation: 1599

You just need to create a subset of period. In this case I created a sub vector to transform into a factor to facilitate the fill.

library(dplyr)
library(ggplot2)

df <- data.frame(paleo.dates = seq(500, 13000, 100),
                 p = runif(n = length(seq(500, 13000, 100)),
                           0, 1))

sub <- data.frame(sub = rep(1:(13000/500), each = 5))
sub <- sub %>%
  dplyr::slice(1:nrow(df))
df <- df %>% 
  dplyr::mutate(period = sub$sub,
                period = as.factor(period))
ggplot2::ggplot(df) +
  geom_bar(aes(x = paleo.dates, y = p, 
               fill = period,
               col = period), 
           show.legend = F, stat = "identity") +
  theme_bw()

enter image description here

Upvotes: 1

Related Questions