2017-05-27 144 views
0

我想繪製一個背景數據集(如下:「bDat」)作爲六邊形框,然後覆蓋來自不同數據集的點(如下:「points」 )。我希望使用ggplot2()來完成此操作,並儘可能使語法與下面提供的MWE保持相似。在ggplot2()中繪製geom_hex()的頂點geom_point()

我能夠得到六角背景下面MWE繪製:

library(ggplot2) 
library(hexbin) 

set.seed(1) 
bDat <- data.frame(Group1 = rnorm(100,0,1), Group2 = rnorm(100,0,1)) 
points <- data.frame(Group1 = rnorm(10,0.5,1), Group2 = rnorm(10,0.5,1)) 
maxVal = max(max(bDat), max(points)) 
minVal = min(min(bDat), min(points)) 
maxRange = c(minVal, maxVal) 
xbins=10 
buffer = maxRange[2]/xbins 
xChar = "Group1" 
yChar = "Group2" 
x = bDat[,c(xChar)] 
y = bDat[,c(yChar)] 
h <- hexbin(x=x, y=y, xbins=xbins, shape=1, IDs=TRUE, xbnds=maxRange, ybnds=maxRange) 
hexdf <- data.frame (hcell2xy (h), hexID = [email protected], counts = [email protected]) 
attr(hexdf, "cID") <- [email protected] 

ggplot(hexdf, aes(x=x, y=y, fill = counts, hexID=hexID)) + 
    geom_hex(stat="identity") + 
    geom_abline(intercept = 0, color = "red", size = 0.25) + 
    coord_cartesian(xlim = c(maxRange[1], maxRange[2]), ylim = c(maxRange[1], maxRange[2])) 

然而,當我在上面MWE改變的最後一個命令,試圖覆蓋的點,我收到一個錯誤的對象hexID未找到:

ggplot(hexdf, aes(x=x, y=y, fill = counts, hexID=hexID)) + 
    geom_hex(stat="identity") + 
    geom_abline(intercept = 0, color = "red", size = 0.25) + 
    coord_cartesian(xlim = c(maxRange[1], maxRange[2]), ylim = c(maxRange[1], maxRange[2])) + 
    geom_point(data = points, aes(x=Group1, y=Group2)) 

錯誤的eval(expr中,ENVIR,enclos):對象 'hexID' 未找到

任何建議,將不勝感激!

+3

加上'inherit.aes = FALSE'到'geom_point' –

回答

2

它的默認行爲是它繼承ggplot對象中已經指定的美學。在你的榜樣,

ggplot(hexdf, aes(x=x, y=y, fill = counts, hexID=hexID)) 

將導致在默認情況下,所有geom_*要求使用這些值的xyfillhexID美學。當所有圖層使用相同的數據集和美學時,這種方式效果很好。

但是,當調用geom_point(data = points, aes(x = Group1, y = Group2))時,fill = countshexID = hexID也隱式傳遞給geom_point

通過塞汀的inherit.aes = FALSE的GEOM

覆蓋默認的美學,而不是 與之結合。這對定義數據和美學的幫助函數 最爲有用,並且不應該繼承默認繪圖規範的行爲 ,例如, 「邊界」。

從你的第一MWE,採取

last_plot() + 
    geom_point(data = points, aes(x=Group1, y=Group2), inherit.aes = FALSE) 

所得的情節是: enter image description here