0

I do not get to add a png background to my plot when using the facet_wrap option. Any idea what should work?

my data is here

library(grid) #complemantory for extra ggplot graphics
library(png) #Add a Background Image in ggplot
library(tidyverse) 

rmsep <- read.csv("rmsep.csv")
rmsep$RA <-  1-(rmsep$rmse/rmsep$sd.price)

plot without background:

rmsep %>%
  ggplot(aes(x = as.factor(month), y = RA, colour = forecast_model)) + 
  geom_point(alpha = 0.6) +
  #scale_fill_manual(values = alpha(model_color, 0.6)) +
  coord_cartesian(ylim = c(-0.4, 0.8)) +
  facet_wrap(~ rmsep$input, ncol = 2) +
  labs(x = "Month", y = "Relative advantage") +
  geom_hline(aes(yintercept = 0))

enter image description here

plot with background:

rmsep %>%
  ggplot(aes(x = as.factor(month), y = RA, colour = forecast_model)) + 
  annotation_custom(rasterGrob(image = background, 
                                width = unit(1,"npc"), 
                                height = unit(1,"npc"))) + 
  geom_point(alpha = 0.6) +
  #scale_fill_manual(values = alpha(model_color, 0.6)) +
  coord_cartesian(ylim = c(-0.4, 0.8)) +
  facet_wrap(~ rmsep$input, ncol = 2) +
  labs(x = "Month", y = "Relative advantage") +
  geom_hline(aes(yintercept = 0))

enter image description here

When combining them, I get the error:

Error in $<-.data.frame(*tmp*, "PANEL", value = c(1L, 1L, 1L, 1L, : replacement has 288 rows, data has 1

1 Answers1

1

You simply need to change rmsep$input to input in the faceting call. You need to facet by the data in the plot's layers, not the original data frame, which of course does not contain your image data.

I didn't have your background image, so I sourced another online:

rmsep %>%
  ggplot(aes(x = as.factor(month), y = RA, colour = forecast_model)) + 
  annotation_custom(rasterGrob(image = background, 
                                width = unit(1,"npc"), 
                                height = unit(1,"npc"))) + 
  geom_point(alpha = 0.6) +
  coord_cartesian(ylim = c(-0.4, 0.8)) +
  facet_wrap(.~input, ncol = 2) +
  labs(x = "Month", y = "Relative advantage") +
  geom_hline(aes(yintercept = 0))

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87