【问题标题】:How to color entire background in ggplot2 when using coord_fixed使用 coord_fixed 时如何在 ggplot2 中为整个背景着色
【发布时间】:2023-04-03 19:35:01
【问题描述】:

coord_fixed() 与 ggplot2 一起使用时,似乎无法设置整个绘图的背景颜色。考虑这个简单的例子:

library(ggplot2)
test_data <- data.frame(x=1:10)
test_data$y <- sqrt(test_data$x)
p1 <- ggplot(test_data) + geom_point(aes(x, y))
p1

我可以轻松地将背景设置为另一种颜色,例如鲜艳的绿色:

p1 + theme(plot.background=element_rect(fill="green"))

但是如果我想使用 coord_fixed() 并将背景涂成绿色怎么办?当我尝试这个ggplot2 在图的底部和顶部留下一条白色条带时:

p1 + theme(plot.background=element_rect(fill="green")) + coord_fixed()

如何完全填充上图的背景(没有顶部和底部的白条)?我在一个循环中生成了许多子图以与animation 包一起使用,我需要确保所有子图的背景都是相同的(非白色)颜色,包括我需要在其上使用@ 987654330@.

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这会做你想做的事:

    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)
    

    首先,我们将边框和填充设置为绿色,然后绘制一个相同颜色的grid 矩形来填充视口,最后我们使用ggplot2:::print 进行绘制,将newpage 参数设置为false 以便它在我们的grid 矩形顶部重叠:

    请注意,问题不在于ggplot,而只是您正在绘制大小错误的视口。如果您将视口预先调整为正确的纵横比,则无需担心先将视口内容设置为绿色。

    【讨论】:

    • 谢谢 - 正是我需要的。
    【解决方案2】:

    如果你想在不依赖非导出的ggplot2函数的情况下达到这个效果,你也可以使用cowplot中的ggdraw()

    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))
    

    ggdraw() 函数将您的绘图包装到一个新的 ggplot 对象中,然后您可以根据需要在该对象上绘制或设置样式。

    【讨论】:

      【解决方案3】:

      ggplot 中有一种方法可以做到这一点,方法是使用秘密(未记录,在... 中传递给设备)参数bgggsave()

      library(ggplot2)
      
      test_data <- data.frame(x = 1:10)
      test_data$y <- sqrt(test_data$x)
      
      p1 <- ggplot(test_data) + 
        geom_point(aes(x, y)) +
        theme(plot.background = element_rect(fill = "green", color = "green")) +
        coord_fixed()
      
      ggsave("test.png", bg = "green", h = 5)
      

      我最初来到这里是因为我使用geom_sf 来绘制根据定义固定为比例的地图,并且想要添加深色背景。 bg 参数也适用于gganimate::animate(),如果您需要为固定比例动画添加背景颜色。

      【讨论】:

      • 我尝试使用 ggsave,但在绘图尺寸方面遇到了一些问题。另一种选择是使用 x11() 为绘图创建图形设备,并使用 savePlot() 来保存它们。
      • 当比率固定且可能未知时,没有简单的方法来自动化绘图尺寸。我喜欢创建自己的保存功能,我将 ggsave 与 magick:: image_read()image_trim()image_write() 结合使用以去除所有空白。
      猜你喜欢
      • 2021-07-20
      • 2019-10-03
      • 2021-10-31
      • 2017-05-22
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      相关资源
      最近更新 更多