r - Plotly:如何为 map 设置 ylim 和 xlim?

标签 r ggplot2 plotly ggplotly

目标:
我正在尝试使用 plotly(通过 ggplotly)创建 ggplot2 map 的交互式版本。
问题: Plotly 在图表上方和下方添加额外的空间,而不是像应有的那样“拉伸(stretch)”图表(例如,参见图片)。
示例
我想要什么(在ggplot2中制作的例子):
enter image description here
我得到了什么(用 plotly 制作的例子):
enter image description here
我知道 ggplotly 不支持 aspect.ratio,但是有没有其他方法可以删除上方和下方的空间,同时保持 x 轴(-12,2)和 y 轴(50,60)的限制不变
代码:

library(maps)
library(ggplot2)
library(plotly)

boundaries <- ggplot2::map_data("world", region=c("UK","Ireland","France","Norway"))

map <- ggplot() +
  geom_polygon(data=boundaries, aes(x=long, y=lat, group=group), color="black", fill="white") +
  coord_sf(xlim=c(-12, 2), ylim=c(50,60)) +
  theme(aspect.ratio = 1.2)

show(map)

visual <- ggplotly(map, height=1.2*400, width=400, tooltip=c("text"), hoverinfo='hide', 
                               dynamicTicks=F) %>%
  layout(xaxis=list(autorange=F, range=c(-12, 2)), yaxis = list(autorange=F, range=c(50,60)))

show(visual)
复制问题:

OS: Windows 10
IDE: RStudio
R: R 3.6.1

最佳答案

您正在使用 coord_sf它适用于特殊类别的 sf 数据帧,而不是 ggplot 附带的多边形.你可以使用像 rnaturalearth 这样的包轻松获取这种格式的数据。在这里,我选择了一个高分辨率的图像,但如果你很难安装 rnaturalearthhires ,只需选择“中”作为 map 大小。

library(ggplot2)
library(plotly)
library(rnaturalearth)
library(sf)

df <- ne_countries(country = c("United Kingdom", "Ireland", "France", "Norway"),
                   returnclass = "sf",
                   scale = "large")

map <- ggplot(df) +
  geom_sf(color = "black", fill = "white") +
  coord_sf(xlim = c(-12, 2), ylim = c(50, 60))

show(map)
enter image description here
我们得到这样的 plotly map :
visual <- ggplotly(map, height = 1.2 * 600, width = 600, tooltip=c("text"), 
                   hoverinfo='hide', dynamicTicks = FALSE) 

show(visual)
enter image description here

关于r - Plotly:如何为 map 设置 ylim 和 xlim?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63271449/

相关文章:

r - 在 R 中排列 4 个 plotly 饼图

r - ggplot2 绘制两条线之间的角度

r - 在 R 中使用 ggplot2 在分类散点图中添加水平线

r - 添加水平线,按因素分组

python - Plotly Python - 热图 - 更改 Hovertext (x,y,z)

R 3.3.0 在 Windows : gcc not found error 上安装软件包

r - 如何在 R 中导入 SVG 文件?

r - 根据多列条件过滤行R

r - 在 R 中 - 找到最小数量的单元格创建小于 n 的组

python - 如何使用 bool 开关更新 Dash 中的图形?