简体   繁体   English

ggplotly和geom_area:将鼠标悬停在某个区域(而非点)上时显示信息

[英]ggplotly and geom_area : display informations when hovering over an area (not a point)

When it comes to a ggplotly graph, it's easy to display informations when hovering over specific point. 关于ggplotly图,将鼠标悬停在特定点上时很容易显示信息。 This code do the job : 这段代码可以完成这项工作:

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)

But I would like to display informations when hovering over one of the area. 但是,当我将鼠标悬停在某个区域上时,我想显示信息。 Because in my case, area is an event that I want to be able to describe deeply. 因为就我而言,区域是我想能够深入描述的事件。

Polygons in ggplot2 ( geom_polygon ) provide a possible solutions. ggplot2多边形( geom_polygon )提供了可能的解决方案。
Below you can find a rather raw code that should clarify the main idea: 在下面,您可以找到一个非常原始的代码,该代码应阐明主要思想:

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")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM