How to color entire background in ggplot2 when using coord_fixed

前端 未结 3 1497
心在旅途
心在旅途 2020-12-06 18:25

When coord_fixed() is used with ggplot2, it does not appear to be possible to set the background color of the entire plot. Consider this simple example:

3条回答
  •  悲&欢浪女
    2020-12-06 19:00

    This will do what you want:

    p2 <- p1 + theme(
      plot.background=element_rect(fill="green", color="green")
    ) + coord_fixed()
    grid:::grid.rect(gp=gpar(fill="green", col="green"))
    ggplot2:::print.ggplot(p2, newpage=FALSE)
    

    First, we set the border and fill to green, then we plot a grid rectangle in the same color to fill the viewport, and finally we plot with ggplot2:::print setting the newpage parameter to false so that it overplots on top of our grid rectangle:

    enter image description here

    Note that the problem isn't with ggplot, but it's just that you are plotting into a viewport that is the wrong size. If you pre-shape your viewport to the correct aspect ratio, you won't need to worry about setting the viewport contents to green first.

提交回复
热议问题