I am trying to reproduce something similar to this map using ggplot2: This is what I've done so far:
load("mapdata.Rdata")
> ls() #2 datasets: "depth" for basemap (geom_contour) and "data" is use to construct geom_bin2d
[1] "data" "depth"
> head(data)
latitude longitude GRcounts
740 67.20000 -57.83333 0
741 67.11667 -57.80000 0
742 67.10000 -57.93333 1
743 67.06667 -57.80000 0
751 67.15000 -58.15000 0
762 67.18333 -58.15000 0
ggplot(data=data,aes(x =longitude, y =latitude))
+theme_bw()
+ stat_bin2d(binwidth = c(0.5, 0.5))
+geom_contour(data=depth,aes(lon, lat, z=dn),colour = "black", bins=5)
+ xlim(c(-67,-56)) + ylim(c(65,71))
Which gives me this map:
The last step is to display over my geom_bin2d circles with size proportional to the sum of the counts (Grcounts) within each bin.
Any tips on how to do so in ggplot (preferably) would be much appreciated.
follow-up question: alignment mismatch between stat_bin2d and stat_summary2d when using facet_wrap
When I run the following code on the diamonds
data set, there are no apparent problem: However if I do run the same code on my data, I do get misalignment problems. Any thoughts on what may cause this problem?
p<-ggplot(diamonds,aes(x =carat, y =price,colour=cut))+
stat_summary2d(fun=sum,aes(z=depth,group=cut),bins=10)
p+facet_wrap(~cut)
df <- ggplot_build(p)$data[[1]]
summary(df)##now 5 groups, 1 panel
df$x<-with(df,(xmin+xmax)/2)
df$y<-with(df,(ymin+ymax)/2)
plot1<-ggplot(diamonds,aes(carat, price))+ stat_bin2d(bins=10)
plot1+geom_point(data=df,aes(x,y,size=value,group=group),color="red",shape=1)+facet_wrap(~group)
This is my Rcode and plot:
p<-ggplot(dat,aes(x =longitude, y =latitude,colour=SizeClass))+
stat_summary2d(fun=sum,aes(z=GRcounts,group=SizeClass),bins=10)
p+facet_wrap(~SizeClass)
df <- ggplot_build(p)$data[[1]]
summary(df)##now 4 groups, 1 panel
df$x<-with(df,(xmin+xmax)/2)
df$y<-with(df,(ymin+ymax)/2)
plot1<-ggplot(dat,aes(longitude, latitude))+ stat_bin2d(bins=10)
plot1+geom_point(data=df,aes(x,y,size=value,group=group),color="red",shape=1)+facet_wrap(~group)
> head(dat[c(7,8,14,21)])###mydata
latitude longitude GRcounts SizeClass
742 67.10000 -57.93333 1 (100,150)
784 67.21667 -57.95000 1 (100,150)
756 67.11667 -57.80000 1 (<100)
1233 68.80000 -59.55000 2 (100,150)
1266 68.68333 -59.60000 2 (100,150)
1288 68.66667 -59.65000 1 (100,150)
My data set can be downloaded here: data
See Question&Answers more detail:os