Reputation: 13
I would like to colour the background of a line plot based on manually inserted coordinates on the x-axis.
As a simple example:
x <- 1:10
y <- c(2.0,2.0,2.1,2.2,2.4,2.7,2.7,2.8,2.8,2.9)
df <- data.frame(x,y)
library(ggplot2)
plot <- ggplot(df, aes(x=x, y=y)) + geom_line()
print(plot)
Now I would like to colour the entire area of the plot between two specified points on the x-axis, say, between 1.5 and 3. Would anyone happen to know an easy manual solution to this?
Upvotes: 1
Views: 22
Reputation: 123903
Maybe this is what you are looking for. You could use a geom_rect
to achieve this:
x <- 1:10
y <- c(2.0,2.0,2.1,2.2,2.4,2.7,2.7,2.8,2.8,2.9)
df <- data.frame(x,y)
library(ggplot2)
ggplot(df, aes(x=x, y=y)) +
geom_rect(xmin = 1.5, xmax = 3, ymin = -Inf, ymax = Inf, fill = "red", inherit.aes = FALSE) +
geom_line()
Created on 2020-12-21 by the reprex package (v0.3.0)
Upvotes: 1