首页 > 解决方案 > 将标签添加到使用 plot_geo 创建的绘图地图

问题描述

我有一个使用plotly::plot_geo. 我想在地图顶部添加标签,例如,在地图上阿拉巴马州的位置上,它会显示“AL (68)”,但对于所有州,如下例所示:

在此处输入图像描述

谁能告诉我是否有办法做到这一点?

library(tidyverse)
library(plotly)

set.seed(1)

density <- sample(1:100, 50, replace = T)

g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  lakecolor = toRGB('white')
)

plot_geo() %>%
  add_trace(
    z = ~density, text = state.name, span = I(0),
    locations = state.abb, locationmode = 'USA-states'
  ) %>%
  layout(geo = g) 

标签: rggplot2plotly

解决方案


使用您的示例,这可以通过plotly::plot_ly()

set.seed(1)

density <- sample(1:100, 50, replace = T)

g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  lakecolor = toRGB('white')
  )

plot_ly() %>%
  layout(geo = g) %>%
  add_trace(type = "choropleth", locationmode = 'USA-states',
            locations = state.abb,
            z = ~density, text = state.name,
            color = ~density, autocolorscale = TRUE) %>%
  add_trace(type = "scattergeo", locationmode = 'USA-states',
            locations = state.abb, text = paste0(state.abb, "\n", density),
            mode = "text",
            textfont = list(color = rgb(0,0,0), size = 12))

输出是:

在此处输入图像描述

仍然不确定如何使用 来执行此操作plotly::plot_geo(),但此解决方案确实允许您留在情节家庭中。


推荐阅读