I want to mark some part of a plot by filling the complete area from some x1 to x2 with (transparent) color in ggplot2
.
With base R I would do something like:
plot(1:100)
polygon(x = c(0, 25, 25, 0), y = c(-1000, -1000, 1000, 1000), col = "#FF000050")
When doing the same with ggplot2
I'm stuck with the problem that the polygon either does not go to the upper and lower edge of the plot or isn't plotted at all if I limit the y-axis with ylim
.
ggplot(data = data.frame(x = 1:100, y = 1:100), aes(x = x, y = y)) +
geom_point() +
#ylim(0, 100) +
geom_polygon(data = data.frame(x = c(0, 25, 25, 0), y = c(-1000, -1000, 1000, 1000)), aes(x = x, y = y), color = "red", fill = "red", alpha = 0.1)
I don't want to limit the solution to geom_polygon
, maybe there is a better way to mark this part of the plot. In my real world data plot, I am using geom_bar
for a stacked barplot, but I don't think the solution depends on that.
You can use
-Inf
and+Inf
to define the limits of thepolygon
(or better in this case, arect
).ggplot2
will ignore them for building the plot limits:Note that I moved the data assignment from the
ggplot
call to thegeom_point
. The motive for this is better explained in this question.Try this: