2017-11-16 4 views
0

ggplotly 그래프의 경우 특정 지점을 가리키면 정보를 쉽게 표시 할 수 있습니다. 이 코드는 다음 작업을 수행합니다.ggplotly 및 geom_area : 특정 지점을 가리키면 정보를 표시합니다.

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

다각형 ggplot2 (geom_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

+0

많은 마르코을 감사 와우 : 아래에서
의 주요 개념을 명확히해야 오히려 원시 코드를 찾을 수 있습니다! 매우 흥미로운 –

관련 문제