Generate diagonal background gradient ggplot2 R

Viewed 108

I have generated a ggplot with following code:

a = rnorm(10000, 0, 0.8)
b = rnorm(10000, 0, 0.8)

#Function to generate correlated vectors
complement <- function(y, rho, x) {
  if (missing(x)) x <- rnorm(length(y))
  y.perp <- residuals(lm(x ~ y))
  rho * sd(y.perp) * y + y.perp * sd(y) * sqrt(1 - rho^2)
}

b = complement(b, 0.9, a)

data = as.data.frame(cbind(a, b, a-b))

blues = adjustcolor(c("white", "dodgerblue3"), alpha=0.4)
blues2 = adjustcolor(c("dodgerblue3", "white"), alpha=0.4)


g <- rasterGrob(t(blues), width=unit(1,"npc"), height = unit(1,"npc"), 
                interpolate = T) 
g2 <- rasterGrob(t(blues2), width=unit(1,"npc"), height = unit(1,"npc"), 
                interpolate = T)

ggplot(data, aes(x=b, y=a)) + theme_classic() + ylab(paste0("\U0394","Ex\n")) + ylim(c(-3.5, 3.5)) + xlab("\n\U0394Int") +
  xlim(c(-3.5, 3.5)) + theme(axis.text.x = element_text(hjust=0.5, size=14, vjust=-0.5), axis.title=element_text(size=16), 
        axis.text.y =element_text(size=12),plot.margin = margin(0.5, 0.5, 0.5, 0.5, "cm")) + 
  annotation_custom(g, xmin=-1.5, xmax=0, ymin=-Inf, ymax=Inf) + annotation_custom(g2, xmin=0, xmax=1.5, ymin=-Inf, ymax=Inf) + 
  geom_point(colour = "grey60", size=2, alpha=0.3)

Which generates the following image:

enter image description here

I would like to repeat the gradient color in blue, but across the diagonal of the plot, using a red gradient.

Does anyone know how to get this? I am able to rotate it to horizontal, but not to diagonal.

Maybe there are more solutions to draw gradient backgrounds other than rasterGrob() and annotation_custom() but I did not manage to get a better way to do what I want, at least for the vertical gradient.

0 Answers
Related