简体   繁体   中英

create hexagonal cells grid using lat/lon coordinates

I would like to create a spatial grid with hexagonal cells using WGS84 coordinates (ie cells defined by 2 coordinates X=Latitude and Y=Longitude)

So, this is what I was thinkin about :

library(ggplot2);library(hexbin)
X<-seq(-10,20,by=0.1) # create coordinates vectors X and Y
Y<-seq(35,65,by=0.1)
z<-rnorm(301,0.5,1)
df<-as.data.frame(cbind(X,Y,z)) # create data frame with a z value for each cells (X,Y)
pl<-ggplot2(data=mat,aes(x=X,y=Y,z=z))+stat_summury_hex(fun=function(x) sum(x))
plot(pl)

But doing this does not provide what I wanted.

So, my question is : how to do a spatial grid with hexagonal cells using lat/lon coordinates ?

And second question : how to create a grid centered from one point (that would represent the centroid, and not the left bottom corner as usual?)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM