【问题标题】:ggplotly maps faulty aspect ratioggplotly 映射错误的纵横比
【发布时间】:2022-08-24 10:11:53
【问题描述】:

我正在尝试使用 plotly 制作一些带有基本工具提示的美国交互式地图。 然而,每当我渲染地图时,绘图的纵横比是“关闭”,地图看起来像是被拉伸了,而且看起来很奇怪。

library(readxl)
library(dplyr)
library(tidyr)
library(urbnmapr)
library(plotly)
library(ggplot2)

states_territory <- urbnmapr::get_urbn_map(map = \"territories_states\",
                                           sf = FALSE)

states_territory <- data.frame(states_territory)

states_territory %>%
  ggplot(aes_string(x = \'long\', 
             y = \'lat\', 
             group = \'group\', 
             text = \'state_name\')) +
    geom_polygon(color = \"#ffffff\", size = 0.25) +
    coord_map(projection = \"albers\", lat0 = 39, lat1 = 45) -> test_plot

plotly_plot <- ggplotly(test_plot,
                        tooltip = \'text\')

plotly_plot

渲染上面的代码应该包含 REPEX 的所有内容,但如果我需要添加一些内容,请告诉我。

这是一个将插入到 Shiny 应用程序中的情节,我让该应用程序正常工作,但我无法让情节获得我希望的干净外观。

如果有人对此或任何其他交互式绘图方法有任何建议,将不胜感激。我已经尝试过 ggiraph,虽然情节看起来不错,但 ggiraph 不会在 R 闪亮的上下文中自动缩放。

谢谢一堆

  • 我不确定,但我想知道它是否与ggplotly() 不知道如何处理coord_map() 有关?此外(可能相关)coord_map()coord_sf() 取代。

标签: r plotly


【解决方案1】:

鉴于以下功能,这是一个相当简单的修复。我最初是从关于 SO 的问答中偷来的。不过我不知道是从谁那里偷来的。

map_aspect = function(x, y) {
  x.center <- sum(range(x)) / 2
  y.center <- sum(range(y)) / 2
  x.dist <- ggplot2:::dist_central_angle(x.center + c(-0.5, 0.5), rep(y.center, 2))
  y.dist <- ggplot2:::dist_central_angle(rep(x.center, 2), y.center + c(-0.5, 0.5))
  y.dist / x.dist
}

您将用以下代码替换 coord_map 以指定纵横比,以便 Plotly 可以继承它。

coord_fixed(with(states_territory, map_aspect(long, lat)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 2013-07-22
    • 2022-08-19
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 2012-07-14
    相关资源
    最近更新 更多