Search code examples
rggplot2annotationsbackground-imagetransparency

While adding a semi transparent layer to background image in r getting Error: Invalid input: date_trans works with objects of class Date only


I am trying to add a semitransparent overlay black layer to background image in r plot. It worked by using annotate and got the solution from: How to add a black overlay semi transparent layer above the background image in r?

Issue: Semi transparent layer doesn't extend completely from left to right over the image of the plot.

If I try use xmin = -Inf, xmax = Inf then it gives error due to date scale xaxis.

So how do i cover the whole image with the layer ?

df

library(tidyverse)
library(lubridate)
library(ggpubr)
library(grid)
library(jpeg)

file_url1 <- "https://raw.githubusercontent.com/johnsnow09/covid19-df_stack-code/main/ts_all_long4.csv"

ts_all_long <- read.csv(url(file_url1))

ts_all_long <- ts_all_long %>%
  mutate(date = as.Date(date))

image used: https://github.com/johnsnow09/covid19-df_stack-code/blob/a00c8820363f2163837d24f801f7c5b85167e0aa/coronavirus-4972480_1920.jpg

ts_all_long %>% 
  filter(Country.Region == "Brazil") %>% 
  
  ggplot(aes(x = date, y = Confirmed_daily)) +
  background_image(readJPEG("/home/johannes/Downloads/coronavirus-4972480_1920.jpg")) +
  annotate("rect", xmin = min(ts_all_long$date), xmax = max(ts_all_long$date), ymin = -Inf, ymax = Inf,
            fill = "black", alpha = 0.3) +
  geom_area(size = 1, col = "#f08080", fill = "#f08080", alpha = 0.5)

enter image description here

If I extend this from -Inf to Inf on xscale: annotate("rect", xmin = min(ts_all_long$date), xmax = max(ts_all_long$date), ymin = -Inf, ymax = Inf, fill = "black", alpha = 0.3) +

then it gives error Error: Invalid input: date_trans works with objects of class Date only


Solution

  • The problem is that the scales::date_trans() transformation doesn't gracefully handle numeric input. I've found a workaround for this issue by manually constructing infinite dates. Example with a standard dataset below:

    library(ggplot2)
    
    ggplot(economics, aes(date, unemploy)) +
      geom_line() +
      annotate("rect", xmin = -Inf, xmax = Inf,
               ymin = -Inf, ymax = Inf, fill = "black", alpha = 0.5)
    #> Error: Invalid input: date_trans works with objects of class Date only
    
    # Manually constructing infinite dates
    ggplot(economics, aes(date, unemploy)) +
      geom_line() +
      annotate("rect", 
               xmin = structure(-Inf, class = "Date"), 
               xmax = structure(Inf, class = "Date"),
               ymin = -Inf, ymax = Inf, fill = "black", alpha = 0.5)
    

    Created on 2021-04-20 by the reprex package (v1.0.0)

    I've argued before that, ideally, the date and time transformations in the scales package should be a little bit more flexible to handle these kind of cases.