在plotly中悬停plot_geo函数的文本

时间:2018-02-21 09:29:19

标签: r plot maps plotly

我想在悬停中显示县名(子区域)和人口值(pop_cat)。

这是我试过的,

  library(tidyverse)
    library(plotly)

    df <- read.csv("https://raw.githubusercontent.com/bcdunbar/datasets/master/californiaPopulation.csv")

    cali <- map_data("county") %>%
      filter(region == 'california')

    pop <- df %>%
      group_by(County.Name) %>%
      summarise(Pop = sum(Population))

    pop$County.Name <- tolower(pop$County.Name) # matching string

    cali_pop <- merge(cali, pop, by.x = "subregion", by.y = "County.Name")

    cali_pop$pop_cat <- cut(cali_pop$Pop, breaks = c(seq(0, 11000000, by = 500000)), labels=1:22)

geo <- list(
  scope = 'usa',
  showland = TRUE,
  landcolor = toRGB("gray95"),
  countrycolor = toRGB("gray80")
)

library(plotly)

geo <- list(
  scope = 'usa',
  showland = TRUE,
  landcolor = toRGB("gray95"),
  countrycolor = toRGB("gray80")
)

p <- cali_pop %>%
  group_by(group) %>%
  plot_geo(
    x = ~long, y = ~lat, color = ~pop_cat, colors = c('#ffeda0','#f03b20'),
    text = ~pop_cat, hoverinfo = 'text') %>%
  add_polygons(line = list(width = 0.4)) %>%
  add_polygons(
    fillcolor = 'transparent',
    line = list(color = 'black', width = 0.5),
    showlegend = FALSE, hoverinfo = 'none'
  ) %>%
  layout(
    title = "California Population by County",
    geo = geo)

p

虽然我在text = ~pop_cat, hoverinfo = 'text'函数中给了plot_geo,但是当我将鼠标悬停在情节上时,它并没有显示出来。当我将鼠标悬停在情节上时,如何显示pop_catsubregion

这是生成的情节。我已经放大了加州地区。

enter image description here

2 个答案:

答案 0 :(得分:3)

情节中存在某种错误。正如@MLavoie所说,您可以在https://github.com/ropensci/plotly/issues/1152

找到解决方案

我尝试使用devly版本的情节,并且已经修复了。同时显示我使用text = ~paste(cali_pop$subregion, "<br />", cali_pop$pop_cat)

的县名和人口

答案 1 :(得分:1)

如果您仍然在从开发人员版本安装后仍然难以获得悬停,并且如果错误显示Error: package or namespace load failed for ‘plotly’ in get(Info[i, 1], envir = env): lazy-load database之类的内容,则只需刷新R-session,这对我有用。

@Harikrishnan的回答。它帮助了我。