7
我正在使用ggplot的geom_tile做一個因素面對的二維密度圖。每個方面的比例從所有數據的最小值到所有數據的最大值,但是每個方面中的geom_tile僅延伸到在該方面中繪製的數據的範圍。如何強制ggplot的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範圍相同的數據,我們看到,無論小面的瓷磚部分延伸到在這種情況下的邊緣。
有什麼辦法可以強制每個方面的geom_tile擴展到整個方面?
不,我希望所有方面都具有相同的比例。基本上,我只想在有限的一側的2x2盒子外面呈現穩定的藍色,以表明那裏的密度爲零。換句話說,我不希望縮放比例縮小到數據範圍,我只想用geom_tile覆蓋整個區域而不改變比例。 –
在這種情況下,您最好手動設置面板背景。我會更新一個例子... – joran
@Ryan - 你也可以看[這裏](http://stackoverflow.com/questions/6906661/ggplot2-make-missing-value-in-geom-tile-not-空白)作爲另一種選擇,但我相信假設您已掌握了密度值。 – joran