r - 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
解决方案
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)
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)
推荐阅读
- angular - 使用反应式表单在 Angular 中检查后,表达式发生了变化
- javascript - 当鼠标快速通过元素时,onMouseEnter 不起作用
- ios - 如何使用 UICollectionViewFlowLayout 使集合中的每个视图居中?
- json - 如何从 SQLITE UNION 查询中获取单个 JSON 对象?
- java - 无法在 Java 应用程序中加载 JDBC 驱动程序类 [oracle.jdbc.driver.OracleDriver]
- php - PHP - 在回调函数的深层传递参数
- javascript - Javascript 对象 ID 字段未传递给事件处理程序
- python - numpy 可以生成大于 64 位的随机数吗?
- angular - 在 Angular 中以模态显示动态数据的问题
- php - phpunit-如何在测试用例中用 mokery 模拟对象