Parsimonious way to add north arrow and scale bar to ggmap

大城市里の小女人 提交于 2019-12-04 03:53:22

It looks like map.scale and north.arrow are designed to work with base graphics, but ggplot uses grid graphics. I'm not that familiar with graphing spatial data, but as a quick hack for the North arrow, the code below includes two different options:

ggmap(map, extent= "device") +
  geom_segment(arrow=arrow(length=unit(3,"mm")), aes(x=33.5,xend=33.5,y=-2.9,yend=-2.6), 
               colour="yellow") +
  annotate(x=33.5, y=-3, label="N", colour="yellow", geom="text", size=4) +
  geom_segment(arrow=arrow(length=unit(4,"mm"), type="closed", angle=40), 
               aes(x=33.7,xend=33.7,y=-2.7,yend=-2.6), colour=hcl(240,50,80)) +
  geom_label(aes(x=33.7, y=-2.75, label="N"),
             size=3, label.padding=unit(1,"mm"), label.r=unit(0.4,"lines"))  

I tend to use my own function to draw scalebars on ggmaps. That gives you the fine control to lay it out exactly how you want it. For example,

scalebar = function(x,y,w,n,d, units="km"){
  # x,y = lower left coordinate of bar
  # w = width of bar
  # n = number of divisions on bar
  # d = distance along each division

  bar = data.frame( 
    xmin = seq(0.0, n*d, by=d) + x,
    xmax = seq(0.0, n*d, by=d) + x + d,
    ymin = y,
    ymax = y+w,
    z = rep(c(1,0),n)[1:(n+1)],
    fill.col = rep(c("black","white"),n)[1:(n+1)])

  labs = data.frame(
    xlab = c(seq(0.0, (n+1)*d, by=d) + x, x), 
    ylab = c(rep(y-w*1.5, n+2), y-3*w),
    text = c(as.character(seq(0.0, (n+1)*d, by=d)), units)
    )
  list(bar, labs)
}

sb = scalebar(33.5, -3.8, 0.05, 5, 0.3, "degrees" )

# Plot map

ggmap(map, extent= "device") +
  geom_rect(data=sb[[1]], aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, fill=z), inherit.aes=F,
            show.legend = F,  color = "black", fill = sb[[1]]$fill.col) +
  geom_text(data=sb[[2]], aes(x=xlab, y=ylab, label=text), inherit.aes=F, show.legend = F) 

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