create hexagonal cells grid using lat/lon coordinates

有些话、适合烂在心里 提交于 2019-12-05 19:38:13

If I understand properly, you're looking for expand.grid():

xy <- expand.grid(X=X,Y=Y)
z<-rnorm(nrow(xy),0.5,1)
df<-as.data.frame(cbind(xy,z)) # create data frame with a z value for each cells (X,Y)
head(df)
pl<-ggplot(data=df,aes(x=X,y=Y,z=z))+stat_summary_hex(fun=function(x) sum(x))
plot(pl)

As for the second question, I'm not sure, but since all hexagons are the same size and will require the same operation to center, you can shift them uniformly by changing X and Y appropriately. Perhaps this can also be done via arguments also, not sure.

[[Edit July 23]] second question was how to get a data.frame of hex coordinates. Took some digging, but here's an example:

library(hexbin)
coords <- hcell2xy( hexbin(x=X,y=Y))
head(coords)
      x        y
1 -10.0 35.00000
2  -9.5 35.86603
3  -8.5 35.86603
4  -9.0 36.73205
5  -8.0 36.73205
6  -7.5 37.59808

hcell2xy() is the key function called by ggplot2, and you may need to be explicit about specifying the argument xbins, which is determined automatically inside ggplot2, but appears to default to 30 in both cases.

[[Edit 3, to include z level]] This is an answer to the comment asking for z levels as well. Ripped from ggplot2:::hexBin

hb <- hexbin(x=X,y=Y)
# Convert to data frame
data.frame(
        hcell2xy(hb), 
        count = hb@count, 
        density = hb@count / sum(hb@count, na.rm=TRUE)
)

You can choose whether to use count or density for colors later, but warning: those are different from your z variable fed to ggplot2. If you'd like to summarize based on some other statistic, then I suggest you also look into the guts of those functions to see how things are passed around. That's what I've been doing.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!