2014-11-14 39 views
2

我正在尝试将工具提示分层到美国地图,但无论我在哪里悬停......它都显示相同的数据。另外,数据是错误的。我在想它是通过了因素值而不是字符值。我试着从电影资源管理器的示例 - http://shiny.rstudio.com/gallery/movie-explorer.html中获取技巧 - 但是,它并不像我所希望的那样工作。任何提示或线索,我应该看看?ggvis地图和工具提示

更新:我确定你只能通过调用ggvis函数的参数。所以,如果我的工具提示功能包括region,long,& lat,它们都会出现在工具提示中。由于PopulationIncome不会出现在函数的任何位置,因此不会传递它们。我仍然不知道如何继续,但任何想法都会很棒! :)

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')  

    } 

) 
+0

可能与[这个问题](http://stackoverflow.com/questions/24493278/ggvis-density-plot-with-tooltip/24498139# 24498139) – Jaap 2014-11-14 17:42:15

回答

2

添加一个索引数据框,你想从拉提示数据:

state$id <- 1:nrow(state) 

ggvis需要一个“关键”的说法,以方便这类工具提示:

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()),我就可以使用它了。

+0

嘿砖,谢谢你的回应!这并不能完全解决我需要的东西,但它确实提供了一些指导。 – maloneypatr 2014-12-09 15:04:54

+0

嘿砖,终于得到了一些更多的修补工作。谢谢! – maloneypatr 2014-12-16 22:34:47

+0

太棒了!我的荣幸! – 2014-12-18 15:41:19

2

我意识到这是相当晚的,但为了将来的参考和其他人在本页面偶然发现。如果您的数据框已经使用fortify进行转换并且具有组变量,那么这可能与州级相当。然后可以使用组来过滤工具提示,因为它在ggvis命令中。这就允许我获得我想要的其他变量。

在我的问题中,我无法使用关键的解决方案,因为我正在创造情节以应对多年。因此,要改变你有以上states_tooltip会变成怎样:

 states_tooltip <- function(x){ 
row <- allstates[allstates$group==x$group,] %>% 
    select(region, Population, Income) %>% unique 
paste0("<b>", row[,"region"], "</b><br>", 
       row[,"Population"], "<br>", 
       row[,"Income"] 
       )})