This code produces the first plot below:
water.height <- seq(0, 5, 1)
y <- seq(0, 1500, length.out = 6)
df <- data.frame(water.height, y)
library(ggplot2)
ggplot(df, aes(water.height, y)) + geom_blank()+ theme_bw()
I have photoshopped in this blue background:
Can I produce the same blue background with R code?
3
Answers
The relevant link to the ggplot2 approach was given in the comments. Copied from there:
My own approach:
As usual, I cannot compete with the simple elegance of baptiste‘s solutions for problems with grid graphics, but here is my approach since I went to all that work:
This modifies the existing background which might be considered an advantage, but in contrast to the
annotation_custom
approach it doesn’t work with faceting. More work would be required for that.We want to use a linear gradient as the background of a plot.
Let’s start by making a matrix with numbers between 0 and 1.
What did we get?
That looks pretty close to what we wanted.
Now, let’s clamp the values between 0 and 1.
Much better!
Let’s use
grid::rasterGrob()
to make a graphical object anddraw it.
Since we have a grob, we can add it to a ggplot2 figure with
ggplot2::annotation_custom()
.Hooray! We did it. But we’re not done yet.
A few notes:
to be faster.
Please feel free to copy the
make_gradient()
function below andimprove upon it.
Example 1
Example 2
Created on 2019-02-06 by the reprex package (v0.2.1)
I used Kamil Slowikowski’s example to build a simpler function that generates linear gradients depending on a series of values. This can be of use if you have a relationship of some kind between three variables (eg.
y~x*z
wherez
also varies overx
). Then you just ploty~x
and havez~x
as a color gradient in the background.To add a legend see here.