4

I want to display the county name(subregion) and the population value(pop_cat) in hover.

Here's what i tried,

  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

Although I gave text = ~pop_cat, hoverinfo = 'text' in plot_geo function, it's not getting displayed when i hover on the plot. What should i do to display both pop_cat and subregion when i hover over the plot.

This is the plot that got generated. I have zoomed in the California region.

enter image description here

2 Answers2

3

There is some kind of bug in plotly. As said by @MLavoie you can find the solution here https://github.com/ropensci/plotly/issues/1152

I tried with the dev version of plotly and it's fixed. Also to display the county name and population i used text = ~paste(cali_pop$subregion, "<br />", cali_pop$pop_cat)

2

If you are still struggling with getting a hover even after installing from developer version, and if the error says something like Error: package or namespace load failed for ‘plotly’ in get(Info[i, 1], envir = env): lazy-load database, just refresh R-session, that worked for me.

@Harikrishnan for your answer. It helped me.

Scott Grammilo
  • 1,229
  • 4
  • 16
  • 37