无法将ggsn比例尺添加到ggplot

时间:2018-04-18 23:01:42

标签: r

我正在尝试使用ggsn :: scalebar()向ggplot地图添加比例尺,但是尽管尝试了许多不同的参数组合,但我总是会遇到一些错误。这是我的地图的代码:

# load libraries
library(tidyverse)
library(viridis)
library(sp)
library(rgdal)
library(ggsn)

# data
my.data.df <- data.frame(value = c(-1.2269832, -1.0153486, -0.9581069, -1.1534667, -1.0139735, -0.8711997, -0.8618286, -0.8524683),
                         x = c(538127.3, 538129.3, 538125.3, 538127.3, 538129.3,538131.3, 538121.3, 538123.3),
                         y = c(1101055, 1101055, 1101053, 1101053, 1101053, 1101053, 1101051, 1101051))
bb <- data.frame(long = c(538107, 538142), lat = c(1101020.5, 1101058.5))


# make a map
my.map <- ggplot(my.data.df, aes(x=x, y=y, fill=value)) +
  geom_tile() +
  geom_path(data = lines, aes(x=long, y=lat, group=group), inherit.aes = FALSE) +
  scale_fill_viridis("Subsidence (m)",
                     limits = c(-1.5, 0.5)) +
  scale_x_continuous(limits = c(538107, 538142)) +
  scale_y_continuous(limits = c(1101020.5, 1101058.5)) +
  coord_fixed() +
  theme(plot.title = element_text(hjust = 0.5),
        axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        legend.justification=c(1,0),
        legend.position=c(1,0),
        plot.margin=unit(c(0,0,0,0), "cm"))

Take a look at the map here.当我尝试向地图添加比例尺时出现问题:

my.map + 
  scalebar(dist = 5, dd2km = FALSE, dist_unit = 'm', location = 'bottomleft')

这将返回错误:

  

比例尺出错(dist = 5,dd2km = FALSE,dist_unit =“m”,location =   “bottomleft”):缺少参数“x.min”,没有默认值

添加x.min,x.max,y.min,y.max:

my.map + 
  scalebar(dist = 5, dd2km = FALSE, dist_unit = 'm', location = 'bottomleft', x.min = 538107, x.max = 538142, y.min = 1101020.5, y.max = 1101058.5)

返回此错误:

  

FUN中的错误(X [[i]],...):找不到对象'值'

尝试添加数据参数:

my.map + 
  scalebar(data = my.data.df, dist = 5, dd2km = FALSE, dist_unit = 'm', location = 'bottomleft', x.min = 538107, x.max = 538142, y.min = 1101020.5, y.max = 1101058.5)

返回错误:

  

错误:data必须是唯一命名的,但具有重复的列In   另外:警告信息:1:在min(数据$ long):没有非缺失   对min的争论;返回Inf 2:在max(数据$ long):没有非缺失   参数max;返回--Inf 3:在min(数据$ lat):没有非缺失   对min的争论;返回Inf 4:在max(数据$ lat):没有非缺失   参数max;返回-Inf

最后,我找到帮助说scalebar()中的data参数实际上是在寻找一个边界框作为数据框,所以我试图使用它:

my.map + 
  scalebar(data = bb, dist = 5, dd2km = FALSE, dist_unit = 'm', location = 'bottomleft', x.min = 538107, x.max = 538142, y.min = 1101020.5, y.max = 1101058.5)

但得到了这个错误:

  

FUN中的错误(X [[i]],...):找不到对象'值'

我想知道添加缩放栏是否会导致ggplot出现问题,因为它不再将“value”识别为数据框中用于填充其中两个尝试的列。但是,我真的不确定。任何见解或解决方案都将非常感谢!

2 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。通过将填充映射从ggplot调用移动到geom_tile调用,它解决了该问题。

答案 1 :(得分:0)

issue已在ggsn v0.4.3中解决。尝试安装开发。版本。

devtools::install_github("oswaldosantos/ggsn")