How to color entire background in ggplot2 when using coord_fixed

前端 未结 3 1498
心在旅途
心在旅途 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 18:59

    If you want to achieve this effect without relying on non-exported ggplot2 functions, you can also use ggdraw() from cowplot:

    test_data <- data.frame(x=1:10)
    test_data$y <- sqrt(test_data$x)
    p1 <- ggplot(test_data) + geom_point(aes(x, y))
    p2 <- p1 + theme(plot.background=element_rect(fill="green", color = NA)) + coord_fixed()
    
    # note, don't load cowplot, since it may change your theme
    cowplot::ggdraw(p2) + 
      theme(plot.background = element_rect(fill="green", color = NA))
    

    The function ggdraw() wraps your plot into a new ggplot object that you can then draw onto or style as you wish.

提交回复
热议问题