I'm using the ggvis package in R to build a build a horizontal stack bar. In the tooltip, I want to add both the absolute and relative values (in percentages).
The following code works, but the tooltip is not formatted correctly yet:
all_values <- function(x) {
if(is.null(x)) return(NULL)
#x[,sapply(x, is.double)] <- apply(x[,sapply(x, is.double)], 1, function(x) {paste(round(100*x, 2), "%", sep="")})
paste0(names(x), ": ",format(x), collapse = "<br />")
}
df <- data.frame(a = c('a','b','c'), v1 = c(7,2,1), v2 = c(0.7,0.2,0.1))
df %>% ggvis(x = ~v1, y = ~a, fill = ~v2) %>%
layer_rects(x2 = 0, height = band()) %>%
add_tooltip(all_values, "hover") %>%
add_tooltip(all_values, "click")
I want to format v2 in such a way that it shows percentages in the tooltip. The values themself (0.7 for example) should still be used as fill.
Removing the commented part in all_values let's the visual crash when hovering for some reason, even though the result of the function would be perfect to me.
Any suggestions?
Something like this?
library(ggvis)
all_values <- function(x) {
if(is.null(x)) return(NULL)
x <- paste0(x[,3]*100,"%")
paste0(names(x), "",format(x), collapse = "<br />")
}
df <- data.frame(a = c('a','b','c'), v1 = c(7,2,1), v2 = c(0.7,0.2,0.1))
df %>% ggvis(x = ~v1, y = ~a, fill = ~v2) %>%
layer_rects(x2 = 0, height = band()) %>%
add_tooltip(all_values, "hover") %>%
add_tooltip(all_values, "click")