悬停时无法访问Plotly中的变量

时间:2018-11-24 16:55:22

标签: r ggplot2 plotly

我为ggplot()的演示文稿准备了一张地图。我想从这张地图上将其转换成一个绘图对象,以便将鼠标悬停在它上面时可以看到更多信息。

library (ggplot2)
library (plotly)

long <- c(-39.98346, -39.99708, -39.97745, -39.90892,-39.73878, -39.73567, -39.76973, -39.95023)
lat <- c(-3.161511, -3.198613, -3.232549, -3.274145, -3.356805, -3.397217, -3.458218,-3.433217)
order <- c(11, 12, 13, 14, 11, 12, 13, 14)
hole <- c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)
piece <- c("1", "1", "1", "1" ,"1" ,"1", "1", "1")
group <- c("20.1" , "20.1" , "20.1" , "20.1" , "203.1", "203.1" ,"203.1", "203.1")
id <- c(20 , 20, 20  ,20 ,203 ,203 ,203, 203)
qty <- c(64.3 ,64.3 ,64.3 ,64.3,38.8, 38.8,38.8 ,38.8)
city <- c("city_A", "city_A", "city_A", "city_A", "city_B", "city_B", "city_B", "city_B" )
map <- data.frame (long,lat,order=as.integer(order),hole,piece,group, id,qty,city,stringsAsFactors = F)

gg_map <- ggplot(data = map)+
geom_polygon(aes(x = long, y = lat, group = group, fill = qty))
gg_map # successfully create the map

plotly_map <- ggplotly(gg_map, tooltip = c("qty", "city")) #conversion of a ggplot map to a plotly map
plotly_map # I cannot visualize city information when hovering

我希望将鼠标悬停在plotly_map上时,我可以同时看到qtycity,但只显示qty。似乎在转换时会丢失与数据帧数据的连接。

我该如何解决?

1 个答案:

答案 0 :(得分:1)

?ggplotly中所说的tooltip参数是

  

一个字符向量,指定要在工具提示中显示哪些美学映射

因此,问题在于citygg_map中不是美学。这是将city用作无用的美感的解决方案:

gg_map <- ggplot(data = map)+
  geom_polygon(aes(x = long, y = lat, group = group, fill = qty, noReason = city))
plotly_map <- ggplotly(gg_map, tooltip = c("qty", "city"))
plotly_map

enter image description here