Plotly:如何为地图设置 ylim 和 xlim?

Bli*_*ing 7 r ggplot2 plotly ggplotly

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

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

例子

我想要什么(在 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)
Run Code Online (Sandbox Code Playgroud)

要复制问题:

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

All*_*ron 6

您正在使用coord_sfwhich 用于特殊类别的 sf 数据帧,而不是随ggplot. 您可以使用类似的包rnaturalearth轻松获取这种格式的数据。在这里,我选择了高分辨率图像,但如果您难以安装rnaturalearthhires,只需选择“中等”作为地图大小。

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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我们得到这样的情节地图:

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

show(visual)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Bli*_*ing 5

有关信息,如果您在 Power BI 服务中使用 R,请按以下方式操作:

您可以通过在布局中的 xaxis 选项中添加scaleratio 来获得所需的结果(请参见下面的代码)。

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)) 

show(map)

visual <- ggplotly(map, height=1.2*400, width=400, tooltip=c("text"), hoverinfo='hide', 
 dynamicTicks=F) %>%
  layout(xaxis=list(scaleratio=0.6))

show(visual)
Run Code Online (Sandbox Code Playgroud)

*根据接受的答案,Power BI 服务不支持 rnaturalearth ( https://learn.microsoft.com/en-us/power-bi/connect-data/service-r-packages-support )

在此输入图像描述