1

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

Community
  • 1
  • 1
janosdivenyi
  • 3,136
  • 2
  • 24
  • 36

1 Answers1

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.

enter image description here

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.

LyzandeR
  • 37,047
  • 12
  • 77
  • 87