如何强制 ggplot 的 geom_tile 填充每个方面?
我正在使用 ggplot 的 geom_tile 来绘制由因子分面的二维密度图。每个方面的比例从所有数据的最小值到所有数据的最大值,但每个方面中的 geom_tile 仅扩展到该方面中绘制的数据的范围。
演示该问题的示例代码:
library(ggplot2)
data.unlimited <- data.frame(x=rnorm(500), y=rnorm(500))
data.limited <- subset(data.frame(x=rnorm(500), y=rnorm(500)), x<1 & y<1 & x>-1 & y>-1)
mydata <- rbind(data.frame(groupvar="unlimited", data.unlimited),
data.frame(groupvar="limited", data.limited))
ggplot(mydata) +
aes(x=x,y=y) +
stat_density2d(geom="tile", aes(fill = ..density..), contour = FALSE) +
facet_wrap(~ groupvar)
运行代码,您将看到两个方面。一个方面显示“无限”随机正态分布的密度图。第二个面显示随机法线,该法线被截断为位于原点周围的 2x2 正方形内。 “有限”构面中的 geom_tile 将被限制在这个小盒子内,而不是填充构面。
last_plot() +
scale_x_continuous(limits=c(-5,5)) +
scale_y_continuous(limits=c(-5,5))
这最后三行使用指定的 x 和 y 限制绘制相同的数据,我们看到两个面都没有扩展图块在这种情况下,部分到边缘。
有没有办法强制每个facet中的geom_tile扩展到facet的整个范围?
I am using ggplot's geom_tile to do 2-D density plots faceted by a factor. Every facet's scale goes from the minimum of all the data to the maximum of all the data, but the geom_tile in each facet only extends to the range of the data plotted in that facet.
Example code that demonstrates the problem:
library(ggplot2)
data.unlimited <- data.frame(x=rnorm(500), y=rnorm(500))
data.limited <- subset(data.frame(x=rnorm(500), y=rnorm(500)), x<1 & y<1 & x>-1 & y>-1)
mydata <- rbind(data.frame(groupvar="unlimited", data.unlimited),
data.frame(groupvar="limited", data.limited))
ggplot(mydata) +
aes(x=x,y=y) +
stat_density2d(geom="tile", aes(fill = ..density..), contour = FALSE) +
facet_wrap(~ groupvar)
Run the code, and you will see two facets. One facet shows a density plot of an "unlimited" random normal distribution. The second facet shows a random normal truncated to lie within a 2x2 square about the origin. The geom_tile in the "limited" facet will be confined inside this small box instead of filling the facet.
last_plot() +
scale_x_continuous(limits=c(-5,5)) +
scale_y_continuous(limits=c(-5,5))
These last three lines plot the same data with specified x and y limits, and we see that neither facet extends the tile sections to the edge in this case.
Is there any way to force the geom_tile in each facet to extend to the full range of the facet?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您正在寻找
scales = "free"
和expand = c(0,0)
的组合:编辑
鉴于OP的澄清,这里有一个选项,只需手动设置面板背景即可:
I think you're looking for a combination of
scales = "free"
andexpand = c(0,0)
:EDIT
Given the OP's clarification, here's one option via simply setting the panel background manually: