将易读的比例尺添加到ggmap中(使用ggsn包?)

时间:2018-08-08 04:21:32

标签: r ggplot2 ggmap

我正在将比例尺插入一些地图中。我使用ggmaps,目前正在使用ggsn包插入比例尺。但是,在我正在使用的地图类型上,很难阅读此比例尺(请参见下面的地图)。我想(a)找到一种使其更易于阅读的方法,(b)使比例尺位于地图边界之外,或者(c)使用其他包,以便更轻松地自定义。

本质上,我的代码看起来像这样。这个例子应该很容易重现。

map <- get_map(location = c(146, 15), zoom = 8,
               maptype = “satellite”, source = "google") 

Map <- ggmap(map)

Map + ggsn::scalebar(x.min = 144.5, x.max = 147.5,
           y.min = 13.5, y.max = 16.5, 
           dist = 50, dd2km = TRUE, model = 'WGS84')

并生成如下图所示的地图,其中右下角的比例尺很难读取。

ggmap with scalebar

有什么想法吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

Github上scalebar的开发版本具有新的参数st.colorbox.fill,可以更好地自定义标尺。

使用以下方法安装该版本:

devtools::install_github('oswaldosantos/ggsn')

然后使用例如

ggmap(Map) + 
  my_scalebar(x.min = 144.5, x.max = 147.5,
            y.min = 13.5,  y.max = 16.5,
            dist = 50, dd2km = TRUE, model = 'WGS84',
            box.fill = c("yellow", "white), st.color = "white")

enter image description here

上级答案

我写了这个答案,内容是在发现较新版本之前如何修改功能。

我认为最好的方法是修改scalebar函数。

首先,您需要加载ggsn软件包并编辑函数:

library(ggsn)
my_scalebar <- edit(scalebar)

这应该弹出一个编辑器。修改函数的顶部,使其看起来像这样:

function (data = NULL, location = "bottomright", dist, height = 0.02, 
  st.dist = 0.02, st.bottom = TRUE, st.size = 5, dd2km = NULL, 
  model, x.min, x.max, y.min, y.max, anchor = NULL, facet.var = NULL, 
  facet.lev = NULL, box2_fill = "yellow", legend_color = "white")
{
  require(maptools)

我们添加了3件事:

  • 默认值为=“ yellow”的自变量box2_fill
  • 默认值为=“ white”的自变量legend_color
  • 需要maptools,因为该函数使用该软件包中的gcDestination()

下一步,寻找以gg.box2开头的行,并将其更改为使用box2_fill的值:

  gg.box2 <- geom_polygon(data = box2, aes(x, y), fill = box2_fill, 
    color = "black")

然后,编辑函数底部附近的部分以使用legend_color的值:

else {
    gg.legend <- annotate("text", label = paste0(legend[, 
      "text"], "km"), x = x.st.pos, y = st.dist, size = st.size,
      color = legend_color)
  }

保存将关闭编辑器,并将新功能my_scalebar保存到您的工作空间。

现在您可以使用新功能了。您可以为新参数box2_fill =legend_color =提供值,也可以尝试使用默认值:

ggmap(Map) + 
  my_scalebar(x.min = 144.5, x.max = 147.5,
            y.min = 13.5,  y.max = 16.5,
            dist = 50, dd2km = TRUE, model = 'WGS84')

如果您认为自己的编辑有用,则可以使用拉取请求at Github向软件包开发人员建议。注意:由于scalebar的Github版本具有新的box.fillst.color参数,因此开发人员似乎已开始解决此问题。