【发布时间】:2018-02-21 09:29:19
【问题描述】:
我想悬停显示县名(子区域)和人口值(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
虽然我在plot_geo 函数中给出了text = ~pop_cat, hoverinfo = 'text',但当我将鼠标悬停在绘图上时它没有显示出来。当我将鼠标悬停在绘图上时,我应该怎么做才能同时显示 pop_cat 和 subregion。
这是生成的情节。我放大了加利福尼亚地区。
【问题讨论】:
-
删除
hoverinfo = 'none'和hoverinfo = 'text'。而且你在df中没有`subregionìn。 -
@MLavoie 谢谢。我现在收到
pop_cat。它还显示了我不想显示的坐标。您能否建议如何删除坐标并添加县名。subregion是县名。它发生在这里,cali <- map_data("county") %>% filter(region == 'california') -
@MLavoie 谢谢!它成功了 :)
-
text = ~pop_cat似乎又可以工作了