As your dataset doesn't work on my computer will use diamonds
dataset as example.
Make new plot of your data with stat_summary2d()
and set z=
as argument you want to sum (in your case GRcounts
) and provide fun=sum
to sum those values. Store it as some object.
p<-ggplot(diamonds,aes(carat,price))+stat_summary2d(fun=sum,aes(z=depth))
Use function ggplot_build()
to get data used for plot. Coordinates of rectangles are in columns xmin
, xmax
, ymin
and ymax
and sum are in column value
.
df <- ggplot_build(p)$data[[1]]
head(df)
fill xbin ybin value ymax ymin yint xmax xmin xint PANEL group
1 #55B1F7 [0.2,0.36] [326,943] 641318.2 942.5667 326.0000 1 0.3603333 0.2000000 1 1 1
2 #1A3955 [0.2,0.36] (943,1.56e+03] 75585.5 1559.1333 942.5667 2 0.3603333 0.2000000 1 1 1
3 #132B43 [0.2,0.36] (1.56e+03,2.18e+03] 415.8 2175.7000 1559.1333 3 0.3603333 0.2000000 1 1 1
4 #132B43 [0.2,0.36] (2.18e+03,2.79e+03] 304.4 2792.2667 2175.7000 4 0.3603333 0.2000000 1 1 1
5 #244D71 (0.36,0.521] [326,943] 179486.8 942.5667 326.0000 1 0.5206667 0.3603333 2 1 1
6 #2D5F8A (0.36,0.521] (943,1.56e+03] 271688.9 1559.1333 942.5667 2 0.5206667 0.3603333 2 1 1
For the points calculate x and y positions as mean of xmin
,xmax
and ymin
,ymax
.
df$x<-with(df,(xmin+xmax)/2)
df$y<-with(df,(ymin+ymax)/2)
Use this new data frame to add points to your original plot with stat_bin2d()
.
ggplot(diamonds,aes(carat,price))+stat_bin2d()+
geom_point(data=df,aes(x=x,y=y,size=value),color="red",shape=1)
UPDATE - solution with facetting
To use facet_wrap()
and combine stat_bin2d()
and points you should use some workaround as there seems to be some problem.
First, create two plots - one for sums with stat_summary2d()
and one for counts with stat_bin2d()
. Both plots should be faceted.
plot1 <- ggplot(dat,aes(x =longitude, y =latitude))+
stat_summary2d(fun=sum,aes(z=GRcounts),bins=10)+facet_wrap(~SizeClass)
plot2 <- ggplot(dat,aes(longitude, latitude))+ stat_bin2d(bins=10)+
facet_wrap(~SizeClass)
Now extract data from both plots using ggplot_build()
and store them as objects. For the sums data frame (df1
) calculated x and y coordinates as in example above.
df1 <- ggplot_build(plot1)$data[[1]]
df1$x<-with(df,(xmin+xmax)/2)
df1$y<-with(df,(ymin+ymax)/2)
df2<-ggplot_build(plot2)$data[[1]]
Now plot your data using those new data frames - df1
for points and df2
for rectangles. With geom_rect()
you will get rectangles which fill=
depend on count. For faceting use column PANEL
.
ggplot()+geom_rect(data=df2,aes(xmin=xmin,xmax=xmax,
ymin=ymin,ymax=ymax,fill=count))+
geom_point(data=df1,aes(x=x,y=y,size=value),shape=1,color="red")+
facet_wrap(~PANEL)