Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 views
in Technique[技术] by (71.8m points)

r - How can I force ggplot's geom_tile to fill every 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)

facet

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

specified limits

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you're looking for a combination of scales = "free" and expand = c(0,0):

ggplot(mydata) +
  aes(x=x,y=y) +
  stat_density2d(geom="tile", aes(fill = ..density..), contour = FALSE) +
  facet_wrap(~ groupvar,scales = "free") + 
  scale_x_continuous(expand = c(0,0)) + 
  scale_y_continuous(expand = c(0,0))

enter image description here

EDIT

Given the OP's clarification, here's one option via simply setting the panel background manually:

ggplot(mydata) +
  aes(x=x,y=y) +
  stat_density2d(geom="tile", aes(fill = ..density..), contour = FALSE) +
  facet_wrap(~ groupvar) + 
  scale_fill_gradient(low = "blue", high = "red") + 
  opts(panel.background = theme_rect(fill = "blue"),panel.grid.major = theme_blank(),
       panel.grid.minor = theme_blank())

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...