使用coord_fixed时如何在ggplot2中为整个背景着色 [英] How to color entire background in ggplot2 when using coord_fixed

查看:126
本文介绍了使用coord_fixed时如何在ggplot2中为整个背景着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

I can easily make the background another color, such as a garish green color:

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

但是,如果我想使用coord_fixed()并将背景颜色设置为绿色怎么办?当我尝试此操作时,ggplot2在图的底部和顶部留下一条白色的条带:

But what if I want to use coord_fixed() and color the background green? When I try this ggplot2 leaves a white strip on the bottom and top of the plot:

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

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

How do I completely fill the background of the above plot (without the white strips on the top and bottom)? I am producing a number of subplots in a loop to be used with the animation package, and I need to ensure the backgrounds of all the subplots are the same (non-white) color, including one on which I need to use 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)

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

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:

请注意,问题出在ggplot上,而不是问题所在,仅仅是因为您正在绘制的视口大小不正确.如果您将视口预成形为正确的宽高比,则无需担心先将视口内容设置为绿色.

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.

这篇关于使用coord_fixed时如何在ggplot2中为整个背景着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆