本文介绍了将标签添加到使用 plot_geo 创建的绘图地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a choropleth map created using plotly::plot_geo. I would like to add labels on top of the map so that, for instance, over the location of Alabama on the map, it would say 'AL (68)', but for all states, as in the example below:

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

Can anyone tell me if there is a way to do this?

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)

推荐答案

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

Using your example, this is possible with 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, "
", density),
            mode = "text",
            textfont = list(color = rgb(0,0,0), size = 12))

输出是:

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

Still not sure how to do this with plotly::plot_geo(), but this solution does allow you to stay within the plotly family.

这篇关于将标签添加到使用 plot_geo 创建的绘图地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:17