将 ggplotly() 与 geom_sf() 一起使用时压扁轴

Squished axis when using ggplotly() with geom_sf()

我正在尝试使用 ggplotly()ggplot 对象变成 plotly 对象。这在使用 sp 对象的整理数据构建 ggplot 时工作正常。但是,使用 geom_sf() 绘图会将 y 轴压缩到绘图高度的一小部分。 (见下面最后一张图片。)

有人知道为什么会这样吗?

library(ggplot2)
library(sf)
library(plotly)
library(broom)

nc <- st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE)

从 sp 对象转换时工作正常

nc_sp <- as_Spatial(nc$geometry)
nc_sp_df <- tidy(nc_sp)
p_sp <- ggplot(nc_sp_df) + geom_polygon(aes(x = long, y = lat, group = group))

p_sp

ggplotly(p_sp)

sf 对象发生了一些奇怪的事情

p_sf <- ggplot(nc) + geom_sf()
p_sf

ggplotly(p_sf)

会话信息

R version 3.4.0 (2017-04-21)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 14.04.2 LTS

Matrix products: default
BLAS: /usr/lib/libblas/libblas.so.3.0
LAPACK: /usr/lib/lapack/liblapack.so.3.0

locale:
[1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8       
[4] LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
[7] LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C              
[10] LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] bindrcpp_0.2       broom_0.4.1        plotly_4.7.1       sf_0.5-5          
[5] ggplot2_2.2.1.9000

问题不在于 sf 与 sp,而是如何巧妙地处理不同的坐标系,即来自 coord_map() 或来自 coord_sf()。 存储库中提出了一些问题:https://github.com/ropensci/plotly/issues/499

如果安装plotly开发版:devtools::install_github('ropensci/plotly'),问题解决

devtools::install_github('ropensci/plotly')
library(sf)
library(ggplot2)
library(plotly)

nc <- st_read(system.file("shape/nc.shp", package="sf"))
p_sf <- ggplot(nc) + geom_sf()

设置宽度和高度参数以避免过多space

ggplotly(p_sf, width = 10, height = 3) 

另请参阅 plotly 开发人员关于将 ggplotly 与 geom_sf() 结合使用的博客 post:https://www.r-bloggers.com/learning-from-and-improving-upon-ggplotly-conversions/