包含堆积条形图中的总值悬停文字

时间:2018-01-03 18:13:07

标签: r

对于具有以下随机值的数据:

structure(list(ActualDateCreated = structure(c(17116, 17118, 
17118, 17118, 17119, 17119, 17119, 17119, 17119, 17119, 17119, 
17119, 17120, 17120, 17120, 17120, 17120, 17120, 17120, 17120, 
17120, 17120, 17121, 17121, 17121, 17121, 17121, 17121, 17121, 
17121, 17121, 17121, 17122, 17122, 17122, 17122, 17122, 17122, 
17122, 17122, 17122, 17123, 17123, 17123, 17123, 17123, 17123, 
17123, 17123, 17124), class = "Date"), Business.Sub.Area = c("Team 1", 
"Team 2", "Team 3", "Team 4", "Team 1", "Team 11", "Team 2", 
"Team 3", "Team 4", "Team 5", "Team 8", "Team 9", "Team 1", "Team 10", 
"Team 11", "Team 2", "Team 3", "Team 4", "Team 5", "Team 7", 
"Team 8", "Team 9", "Team 1", "Team 10", "Team 11", "Team 2", 
"Team 3", "Team 4", "Team 5", "Team 7", "Team 8", "Team 9", "Team 1", 
"Team 10", "Team 11", "Team 2", "Team 3", "Team 4", "Team 5", 
"Team 8", "Team 9", "Team 1", "Team 11", "Team 3", "Team 4", 
"Team 5", "Team 6", "Team 7", "Team 9", "Team 1"), n = c(80L, 
86L, 32L, 32L, 67L, 31L, 54L, 94L, 92L, 44L, 50L, 47L, 38L, 76L, 
75L, 60L, 55L, 78L, 89L, 70L, 34L, 76L, 38L, 93L, 84L, 13L, 90L, 
95L, 62L, 7L, 70L, 23L, 67L, 32L, 12L, 66L, 8L, 20L, 30L, 79L, 
14L, 73L, 89L, 4L, 23L, 15L, 31L, 27L, 28L, 2L)), .Names = 
c("ActualDateCreated", 
"Business.Sub.Area", "n"), row.names = c(NA, -50L), class = c("tbl_df", 
"tbl", "data.frame"))

我有以下情节:

plot_ly(dailycct[dailycct$ActualDateCreated >= "2017-11-01",], 
    type      = 'bar',  
    x         = ~ActualDateCreated, 
    y         = ~n, 
    color     = ~Business.Sub.Area,
    text      = ~paste('Date: ', ActualDateCreated, '\n',
                       'Team: ', Business.Sub.Area, '\n',
                       'Count: ', n, '\n',
                       'Total: ', sum(n),'\n'),
    hoverinfo = 'text'
) %>%
  layout(yaxis = list(title = 'Count'), barmode = 'stack')

enter image description here

正如您所看到的,总计'悬停文本中的部分是整个数据集的总和,而不是光标仅悬停在其上的日期的总和。有没有办法在光标悬停的日期获得n的总数?

1 个答案:

答案 0 :(得分:1)

一种方法是在数据集中添加一列,以便在每个日期提供一个包含总计的附加列。您可以使用dplyr执行此操作。然后在图中使用这个新列,如下所示:

library(dplyr)
library(plotly)


     df <- dailycct[dailycct$ActualDateCreated >= "2016-11-01",]

     df <- df %>% group_by(ActualDateCreated) %>% mutate(nTotal = sum(n)) 

     plot_ly(df, 
             type      = 'bar',  
             x         = ~ActualDateCreated, 
             y         = ~n, 
             color     = ~Business.Sub.Area,
             text      = ~paste('Date: ', ActualDateCreated, '\n',
                                'Team: ', Business.Sub.Area, '\n',
                                'Count: ', n, '\n',
                                'Total: ', nTotal,'\n'),
             hoverinfo = 'text'
     ) %>%
       layout(yaxis = list(title = 'Count'), barmode = 'stack')  

通过这个,你得到一个如下图:enter image description here