R 的 ggvis 工具提示 layer_paths

Tooltip in ggvis for R with layer_paths

我对 ggvis 中的工具提示功能有疑问,因为我的等值表 plot.I 在下面附上了我的代码。代码 运行 很好,没有工具提示功能。但是,如果我添加工具提示,则只剩下新泽西州的土地(见图)。其他州都不见了。任何人都可以帮忙看看,我该如何修复它以通过添加工具提示功能恢复其他部分?非常感谢!

###my data for example
mapdata<-data.frame(
  state=c("alabama","alaska","arizona","arkansas","california","colorado","connecticut","delaware","florida","georgia","hawaii","idaho","illinois","indiana","iowa","kansas","kentucky","louisiana","maine","maryland","massachusetts","michigan", "minnesota","mississippi","missouri","montana","nebraska","nevada","new hampshire","new jersey","new mexico","new york","north carolina","north dakota","ohio","oklahoma", "oregon","pennsylvania","rhode island","south carolina","south dakota","tennessee","texas","utah","vermont","virginia","washington","west virginia","wisconsin","wyoming"),
  revenue=runif(50,min=100,max=9000))

library(rgdal)   
library(ggplot2) 
library(ggvis)

url   <- "http://www2.census.gov/geo/tiger/GENZ2014/shp/cb_2014_us_state_20m.zip"
tf    <- tempfile()
td    <- tempdir()
download.file(url,tf, mode="wb")  
unzip(tf, exdir=td)                

usa <- readOGR(dsn=td, layer="cb_2014_us_state_20m")
shp <- usa[(!usa$STUSPS %in% c("AK","HI")),] 

df<- fortify(shp)                    
df<- merge(df,cbind(id=rownames(shp@data),shp@data),by="id")   
df$state <- tolower(df$NAME)                                                  
df<- merge(df,mapdata,by="state")  
df<- df[order(df$order),]       

####function for tooltip
gg<-df
gg$id<-1:nrow(gg)
values<-function(x){
  if(is.null(x)) return(NULL)
  row<-gg[gg$id==x$id,]
  paste0("State: ",row$state,"<br />",
         "Revenue: ", row$revenue, "<br />")
}
####ggvis choropleth
gg %>%
  group_by(group) %>%
  ggvis(~long, ~lat, key:=~id)  %>%
  hide_axis("x") %>% 
  hide_axis("y")%>%
  add_tooltip(values,"hover")%>%
  layer_paths(fill= ~revenue)

我环顾四周,意识到由于路径是由来自数据集多行的信息组成的,因此像我们通常使用的那样尝试为工具提示使用唯一的行 ID 没有意义 key.

然后我看到这个very nice ggvis tutorial,前进的方向对我来说变得更加清晰。您需要将工具提示基于您的 grouping 变量,然后以某种方式将该组中的许多行的信息筛选为单个值。在其他选项中,您可以通过仅从组中拉出第一行或在您的工具提示函数中使用 unique 值来实现。

这是我的意思的示例,使用您在 group_by 中使用的变量 group 来提取相关信息。

首先,使用 head 得到第一行:

values = function(x){
    if(is.null(x)) return(NULL)
    row = head(gg[gg$group == unique(x$group), ], 1)
    paste0("State: ", row$state,"<br />",
           "Revenue: ", row$revenue, "<br />")
}

或者,只需拉出要显示的变量的 unique 值(每个 state/group 有一个)。这在你的情况下工作正常,因为你只显示两个值:

values2 = function(x){
    if(is.null(x)) return(NULL)
    row = gg[gg$group == unique(x$group), ]
    paste0("State: ", unique(row$state),"<br />",
           "Revenue: ", unique(row$revenue), "<br />")
}

现在从 ggvis 中取出 key 参数并使用其中一个新的工具提示功能。现在交互式图表似乎工作正常。

gg %>%
    group_by(group) %>%
    ggvis(~long, ~lat)  %>%
    hide_axis("x") %>% 
    hide_axis("y")%>%
    add_tooltip(values, "hover")%>%
    layer_paths(fill= ~revenue)