首页 > 解决方案 > Plotly:如何为地图设置 ylim 和 xlim?

问题描述

目标: 我正在尝试使用 plotly(通过 ggplotly)创建 ggplot2 地图的交互式版本。

问题:在图表上方和下方增加额外的空间,而不是像应该的那样“拉伸”图表(例如,参见图片)。

例子

我想要什么(在ggplot2中制作的例子):

在此处输入图像描述

我得到了什么(用情节制作的例子):

在此处输入图像描述

我知道 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)

要复制问题:

操作系统:Windows 10
IDE:RStudio
R:R 3.6.1

标签: rggplot2plotlyggplotly

解决方案


You are using coord_sf which is intended for the special class of sf data frames rather than the polygons that come with ggplot. You could use a package like rnaturalearth to easily obtain data in this format. Here, I have selected a high-res image, but if you struggle to install rnaturalearthhires, just select "medium" for map size.

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

and we get the plotly map like this:

visual <- ggplotly(map, height = 1.2 * 600, width = 600, tooltip=c("text"), 
                   hoverinfo='hide', dynamicTicks = FALSE) 

show(visual)

enter image description here


推荐阅读