r - Plot series of filled hexagons in ggplot2 -
i trying create tesselation of filled hexagons (polygons centered around hexagonally-spaced lattice) in ggplot2. have accomplished using 'plot' command struggling transitioning ggplot.
here code set-up:
# generate lattice of points equally spaced in centers of hexagonal lattice dist = 1 # distance between centers of hexagons nx = dist*15 # horizontal extent ny = dist*15 # vertical extent makehexlattice = function(nx, ny, dist, origin=c(0,0)) { locations = cbind(location = 1:(nx*ny), x = sort(c(rep(seq(from=0, by=dist, length.out=nx),each=ceiling(ny/2)), rep(seq(from=dist/2, by=dist, length.out=nx), each=floor(ny/2)))) + origin[1], y = rep(c(seq(from=0, = dist*sqrt(3), length.out=ceiling(ny/2)), seq(from=dist*sqrt(3)/2, by=dist*sqrt(3), length.out=floor(ny/2))) + origin[2], times=nx)) class(locations) = c(class(locations), "lattice") attr(locations, "gridsize") = dist return(locations) }
here code creating image using 'plot', looks nice:
landscape = makehexlattice(nx=nx,ny=ny,dist=dist,origin=c(0,0)) # plot hexagonal lattice points plot(x=landscape[,2],y=landscape[,3], pch=19, col="black", cex=0.5, asp=1/1) # separate x , y coordinates lx = landscape[,2] # x-coordinates ly = landscape[,3] # y-coordinates # plot hexagonal lattice filled hexagons hex.x = cbind(lx + 0, lx + 0.5, lx + 0.5, lx + 0, lx - 0.5, lx - 0.5) hex.y = cbind(ly - 1/(sqrt(3)), ly - 1/(2*sqrt(3)), ly + 1/(2*sqrt(3)), ly + 1/(sqrt(3)), ly + 1/(2*sqrt(3)), ly - 1/(2*sqrt(3))) hex.vectors = cbind(hex.x, hex.y) for(i in 1:(length(hex.vectors)/12)){ polygon(x=hex.vectors[i,1:6], y=hex.vectors[i,7:12], angle = 120, border=null, col="wheat", lty = par("lty"), filloddeven = false) }
any tips on how accomplish same thing using ggplot2 (which transitioning using)? have tried using geom_polygon can't seem work out for-loop. (also, please don't tell me use 'hexbin' -- not goal trying accomplish!)
thank help!
as things in ggplot, plotting extremely straightforward, of work getting data in right shape makes sense. for
loop entirely unnecessary, geom_polygon()
needs dataframe x , y coordinates, , variable defining group belong to. data:
library(ggplot2) library(reshape2) #get coordinates in long format id hexdat.x <- melt(cbind(id = 1:length(hex.x), as.data.frame(hex.x)), id.vars = "id", value.name = "x") hexdat.y <- melt(cbind(id = 1:length(hex.y), as.data.frame(hex.y)), id.vars = "id", value.name = "y") #merge them same dataframe hexdat <- merge(hexdat.x, hexdat.y) head(hexdat) # id variable x y # 1 1 v1 0.0 -0.5773503 # 2 1 v2 0.5 -0.2886751 # 3 1 v3 0.5 0.2886751 # 4 1 v4 0.0 0.5773503 # 5 1 v5 -0.5 0.2886751 # 6 1 v6 -0.5 -0.2886751
now plot hexagons, need give ggplot
x , y coordinates, , specify group each 1 belongs to:
ggplot(hexdat, aes(x, y)) + geom_polygon(aes(group = id), fill = "wheat", colour = "black")
Comments
Post a Comment