Squished axis when using ggplotly() with geom_sf()

时间:2018-04-18 17:44:38

标签: r ggplot2 plotly spatial sf

I am trying to use ggplotly() to turn a ggplot object into a plotly object. This works fine when building the ggplot with tidied data from an sp object. However, plotting with geom_sf() squishes the y-axis to a fraction of the plot height. (See last image below.)

Does anyone know why this is happening?

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

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

Works fine when converting from sp object

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

ggplot_sp

ggplotly(p_sp)

plotly_sp

Something strange happens with sf objects

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

ggplot_sf

ggplotly(p_sf)

plotly_sf

Session info

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

1 个答案:

答案 0 :(得分:1)

问题不是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()

设置宽度和高度参数以避免多余空间

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

enter image description here

也可以看一下情节开发人员使用ggplotly和geom_sf()看到这篇博文:https://www.r-bloggers.com/learning-from-and-improving-upon-ggplotly-conversions/