ggplotly和geom_area:悬停在某个区域(不是某个点)时显示信息

时间:2017-11-16 13:46:47

标签: r hover tooltip plotly ggplotly

当涉及ggplotly图时,在悬停在特定点上时很容易显示信息。这段代码完成了这项工作:

toy_df=data.frame("t"=c(seq(1,10),seq(1,10)),
                  "value"=c(runif(10,0,10),2*runif(10,0,10)),
                  "event"=c(rep("A",10),rep("B",10)))

p <- ggplot() + geom_area(aes(y = value, x = t, fill=event), data = toy_df)
ggplotly(p)

但我想悬停在其中一个区域时显示信息。因为在我的情况下,区域是我希望能够深刻描述的事件。

1 个答案:

答案 0 :(得分:1)

ggplot2geom_polygon)中的多边形提供了一种可能的解决方案 下面你可以找到一个相当原始的代码,它应该澄清主要的想法:

library(ggplot2)
library(plotly)
set.seed(1)
toy_df=data.frame("t"=c(seq(1,10),seq(1,10)),
                  "value"=c(runif(10,0,10),2*runif(10,0,10)),
                  "event"=c(rep("A",10),rep("B",10)))

# In order to create polygons like in geom_areas,
# two points on the x-axis must be added: one at t=1 and one at t=10
toy_df2 <- toy_df[NULL,]
for (k in unique(toy_df$event)) {
 subdf <- subset(toy_df, toy_df$event==k)
 nr <- nrow(subdf)
 row1 <- subdf[1,]
 row1$value <- 0
 row2 <- subdf[nr,]
 row2$value <- 0
 toy_df2 <- rbind(toy_df2, row1, subdf, row2)
}
# Stack polygons 
toy_df2$value[toy_df2$event=="A"] <- toy_df2$value[toy_df2$event=="A"] + 
                                     toy_df2$value[toy_df2$event=="B"]

# Calculate mean values for the two events: they will be displayed in the tooltip
toy_df2 <- toy_df2 %>% group_by(event) %>% mutate(mn=round(mean(value),3))

p <- ggplot(data = toy_df2, aes(y = value, x = t, fill=event, 
            text=paste0("Value:", mn,"<br>Event:", event))) + 
     geom_polygon()
ggplotly(p, tooltip="text")

enter image description here