Reputation:
I am creating a plot of hexbin data in R, in which the color represents the number of data points in each hexbin. I seem to have this working as is shown in the MWE below:
library(hexbin)
library(ggplot2)
set.seed(1)
data <- data.frame(A=rnorm(100), B=rnorm(100), C=rnorm(100), D=rnorm(100), E=rnorm(100))
maxVal = max(abs(data))
maxRange = c(-1*maxVal, maxVal)
x = data[,c("A")]
y = data[,c("E")]
h <- hexbin(x=x, y=y, xbins=5, shape=1, IDs=TRUE, xbnds=maxRange, ybnds=maxRange)
hexdf <- data.frame (hcell2xy (h), hexID = h@cell, counts = h@count)
p <- ggplot(hexdf, aes(x=x, y=y, fill = counts, hexID=hexID)) + geom_hex(stat="identity") + coord_cartesian(xlim = c(maxRange[1], maxRange[2]), ylim = c(maxRange[1], maxRange[2]))
I am now trying to superimpose a subset of the original data in the form of points on top of the hexbin plot. I first create the subset of the original data as follows:
dat <- data[c(1:5),]
Then, I tried to plot these five data points onto the hexbin plot, p:
p + geom_point(data = dat, aes(x=A, y=B))
For which I receive the Error: "Error in eval(expr, envir, enclos) : object 'counts' not found". I also tried the following:
p + geom_point() + geom_point(dat, aes(A, B))
For which I receive the Error: "Error: ggplot2 doesn't know how to deal with data of class uneval".
I tried several new ideas based on similar posts - but would always have an error and no resulting plot. I am wondering if such a technique is possible. If anyone has ideas to share, I would very much appreciate your input!
Upvotes: 1
Views: 750
Reputation: 10771
To solve this problem, we need to set inherit.aes = FALSE
in your geom_point
call. Basically, you've set the fill
aesthetic equal to count
in your ggplot
call, so when ggplot
tries to add the points to the plot, it looks for count
in dat
. ggplot
is telling you "hey, I can't find count
in this data set, so I can't add that geom
since it's missing an aes".
p + geom_point(data = dat, aes(x=A, y=B),
inherit.aes = FALSE)
Or, we could define p
as:
p <- ggplot() +
geom_hex(data = hexdf, aes(x=x, y=y, fill = counts), stat="identity") +
coord_cartesian(xlim = c(maxRange[1], maxRange[2]), ylim = c(maxRange[1], maxRange[2]))
And then we wouldn't need inhert.aes
:
p + geom_point(data = dat, aes(x = A, y = B))
Upvotes: 2