Mark range in plot with transparent color

2019-07-27 22:51发布

问题:

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.

回答1:

You can use -Inf and +Inf to define the limits of the polygon (or better in this case, a rect).
ggplot2 will ignore them for building the plot limits:

ggplot() +
    geom_point(data = data.frame(x = 1:100, y = 1:100), aes(x = x, y = y)) +     
    geom_polygon(data = data.frame(x = c(0, 25, 25, 0), y = c(-Inf, -Inf, Inf, Inf)), aes(x = x, y = y), color = "red", fill = "red", alpha = 0.1) +
    geom_rect(aes(xmin = 30, xmax = 35, ymin = -Inf, ymax = Inf), color = 'green',  fill = "green", alpha = .1)

Note that I moved the data assignment from the ggplot call to the geom_point. The motive for this is better explained in this question.



回答2:

Try this:

ggplot(data = data.frame(x = 1:100, y = 1:100), aes(x = x, y = y)) +
  geom_rect(aes(xmin = 0, xmax = 25, ymin = 0, ymax = 100), fill = "red", alpha = 0.01)+
  geom_point()+
  scale_y_continuous(limits = c(0, 100), expand = c(0, 0))


标签: r ggplot2