我正在尝试将工具提示分层到美国 map 上,但无论我将鼠标悬停在何处......它都会显示相同的数据。另外,数据有误。我认为它是通过因子值而不是字符值。我尝试从电影资源管理器示例中获取提示 - http://shiny.rstudio.com/gallery/movie-explorer.html -但是,它并没有像我希望的那样工作。我应该研究什么提示或线索吗?
更新:我确定您只能传递正在调用到 ggvis 函数的参数。因此,如果我的工具提示函数包含 region
、long
和 lat
,它们都会出现在工具提示中。由于 Population
和 Income
没有出现在函数中的任何位置,因此它不会传递它们。我仍然不知道如何继续,但任何想法都会很棒! :)
library(ggplot2)
library(shiny)
library(ggvis)
library(dplyr)
shinyApp(
ui = fluidPage(
#numericInput("n", "n", 1),
ggvisOutput("map")
),
server = function(input, output) {
statesData <- reactive({
states <- data.frame(state.x77)
states$region <- row.names(state.x77) %>% tolower
row.names(states) <- NULL
all_states <- map_data("state") %>%
mutate(region = tolower(region)) %>%
left_join(states)
all_states_unique <- all_states %>%
select(region, Population, Income, Illiteracy, Life.Exp, Murder, HS.Grad, Frost, Area) %>%
unique
states_tooltip <- function(x) {
if (is.null(x)) return(NULL)
if (is.null(x$region)) return(NULL)
# Pick out the movie with this ID
allStates <- isolate(all_states_unique)
state <- allStates[allStates$region == x$region, ]
paste0("<b>", state$region, "</b><br>",
state$Population, "<br>",
state$Income
)
}
all_states %>%
arrange(group, order) %>%
ggvis(x = ~long, y = ~lat) %>%
layer_paths(fill = ~region, stroke := .2) %>%
add_tooltip(states_tooltip, "hover")
})
statesData %>% bind_shiny('map')
}
)
最佳答案
向要从中提取工具提示数据的数据框添加索引:
state$id <- 1:nrow(state)
ggvis 采用“key”参数来促进这种工具提示:
ggvis(x = ~long, y = ~lat, key := ~id) %>%
我尝试找出那个电影示例,但发现它没有太大帮助。这对我来说总是有效:
add_tooltip(function(x) {
row <- state[state$id == x$key,]
paste0("<b>", row[,"region"], "</b><br>",
row[,"Population"], "<br>",
row[,"Income"]
)})
至于工具提示总是出现相同的问题,我不确定,但认为这是由于 ggvis 命令中图层的顺序造成的。有一个类似的问题,我在散点图上分层放置了一些多边形。当我想要的是显示工具提示的各个点时,它一直尝试绘制多边形的工具提示(覆盖整个图表)。通过在 ggvis 命令中反转它们的顺序(即 layer_points() %>% layer_shapes()),我让它工作了。
关于r - ggvis map 和工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26935275/