Add a geom_rect to the plot background (not panel)

2019-08-27 15:06发布

问题:

I have attached a screenshot of a 538 plot - https://scontent-lax3-2.xx.fbcdn.net/v/t31.0-8/22218477_1588451034532053_5652546964446428775_o.png?oh=aa7436a960f2982deed7a90c997f31e4&oe=5A45A9E7 - and I am trying to format my ggplot in a similar manner. The part I am currently struggling with is the dark grey shading on the bottom. I have a demo plot here:

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + 
  geom_point() + 
  theme(plot.background = element_rect(fill = 'gray95'),
        panel.background = element_rect(fill = 'red')) + 
  labs(caption = 'mycaption')

panel.background colors the entire panel red, and plot.background colors everything to the outside of the panel grey. I am familiar with geom_rect(), however these can only be placed INSIDE the panel from what I've read, with parameters for xmin/xmax/ymin/ymax... Is there anyway for me to add a geom_rect() on the bottom of the ENTIRE GRAPH, and not simply the bottom of the panel between x and y coordinates?

Let me know if this makes sense at all, otherwise I can explain more.

Thanks!

回答1:

there are already several answers on this site; here's one approach:

library(gridExtra)
fthbar <- grobTree(rectGrob(gp=gpar(fill="grey50",col=NA)),
                   textGrob("LEFT", x=0, hjust=0, gp=gpar(col="white")), 
                      textGrob("RIGHT", x=1, hjust=1, gp=gpar(col="white")), cl="ann")
heightDetails.ann <- function(x) unit(1,"line")
grid.arrange(qplot(rnorm(10),rnorm(10)), bottom = fthbar)



回答2:

I don't know of a way to accomplish that directly in ggplot, but you can certainly do it with the more general power of the grid package. I have found this tutorial to be helpful in getting started with it if you haven't used it before. You can pretty generally lay out a page with ggplot graphs placed on it as you like.

Alternatively, you can check out the cowplot package. It also allows you to lay out a page a little more simply and accomplish a lot of the grid functionality a little more simply. You should be able to figure out how to do what you desire from the documentation.



标签: r ggplot2