在ggplot2()中的geom_hex()上绘制geom_point()

时间:2017-05-27 16:49:50

标签: r ggplot2

我正在尝试将背景数据集(下面:“bDat”)绘制为六边形区域,然后覆盖来自不同数据集的点(下方:“点”)。我想使用ggplot2()完成此操作,并保持语法尽可能与下面提供的MWE类似。

我能够用下面的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 = h@cell, counts = h@count)
attr(hexdf, "cID") <- h@cID

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'

任何建议都将不胜感激!

1 个答案:

答案 0 :(得分:1)

geoms的默认行为,它继承了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