How to add tooltip with shares to ggvis histogram?

梦想与她 提交于 2020-01-05 08:53:15

问题


I would like to create an interactive histogram which gives information about the bins by hover. This thread gives answer to how to add tooltip with count numbers.

library("ggvis")

cocaine %>%  
    ggvis(x = ~weight) %>%
    layer_histograms() %>%
    add_tooltip(function(df) (paste("count:", df$stack_upr_ - df$stack_lwr_)))

How can I add the share of each bin as well? I should somehow add nrow(cocaine) to ggvis and create the shares from count but I did not succeed on how to achieve that (tried to take the suggestions of this post but apparently that solves a different problem).


回答1:


You could do something like this I imagine:

cocaine %>%  
  ggvis(x = ~weight) %>%
  layer_histograms() %>%
  add_tooltip(function(df) paste("count:", df$stack_upr_, 'share:', 
                           format(df$stack_upr_/nrow(cocaine), digits=2)))

This will show both the share and the bin number.

Also, as a side note you do not need df$stack_upr_ - df$stack_lwr_ because df$stack_lwr_ will be zero. Just df$stack_upr_ will do.



来源:https://stackoverflow.com/questions/34002498/how-to-add-tooltip-with-shares-to-ggvis-histogram

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!