当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
Run Code Online (Sandbox Code Playgroud)

我可以轻松地使背景成为另一种颜色,例如扎眼的绿色:
p1 + theme(plot.background=element_rect(fill="green"))
Run Code Online (Sandbox Code Playgroud)

但是,如果我想使用coord_fixed()并将背景颜色设置为绿色怎么办?当我尝试时,这ggplot2会在情节的底部和顶部留下一条白色的条:
p1 + theme(plot.background=element_rect(fill="green")) + coord_fixed()
Run Code Online (Sandbox Code Playgroud)

如何完全填充上述图的背景(顶部和底部没有白色条纹)?我正在循环使用该animation包来制作多个子图,并且需要确保所有子图的背景是相同的(非白色)颜色,包括我需要使用的颜色coord_fixed()。
这将执行您想要的操作:
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)
Run Code Online (Sandbox Code Playgroud)
首先,我们将边框和填充设置为绿色,然后我们绘制一个grid相同颜色的矩形以填充视口,最后我们ggplot2:::print将newpage参数设置为 false 进行绘制,以便它在我们的grid矩形顶部重叠:

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