我对ggvis中的工具提示函数有困难,因为我的等值线图。我在下面附上了我的代码。代码运行良好,没有工具提示功能。但如果我添加工具提示,只剩下新泽西的土地(见图)。其他州缺失。任何人都可以帮助看看,我如何修复它以添加其他部分添加工具提示功能?非常感谢!
###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)
答案 0 :(得分:4)
我正在四处寻找并意识到由于路径是来自数据集的多行信息,因此尝试使用工具提示的唯一行ID是没有意义的,就像我们通常使用{{1 }}
然后我看到了这个very nice ggvis tutorial,前进的道路对我来说变得更加清晰。您需要将工具提示基于分组变量,然后以某种方式将该组中许多行的信息提取到单个值。在其他选项中,您可以通过从组中取出第一行或在使用工具提示功能时仅使用key
值来实现此目的。
以下是我的意思的示例,使用您在unique
中使用的变量group
来提取相关信息。
首先,使用group_by
获取第一行:
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
现在从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 />")
}
中取出key
参数并使用其中一个新的工具提示函数。现在,交互式图表似乎工作正常。
ggvis