2014-11-14 52 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"] 
       )})