ggvis multiple lines with tooltips

感情迁移 提交于 2019-12-24 03:33:03

问题


I am trying to create an interactive Version of this plot:

So far I have the following code that creates an interactive plot but is not exactly what I am looking for:

#Create Data
library(ggvis)
set.seed(123)
tdat <- data.frame(group = rep(LETTERS[1:2], each = 50),
               time = rep(seq(from = as.Date("2010-01-01"), length.out = 50, by = "day"), 2),
               val = c(cumsum(rnorm(50)) + 100,
                       cumsum(rnorm(50)) + 100))

# ggvis Code
# Function for the tooltip
getData <- function(dat){
    paste(paste("Time:", as.character(dat$time)),
    paste("Group:", as.character(dat$group)),
    paste("Value:", dat$val),
    sep = "<br />")
}

# Visualisation
tdat %>% ggvis(~time, ~val, stroke = ~group) %>% layer_lines(strokeWidth := 1) %>%
     layer_points(size = 1, fill = ~group) %>% add_tooltip(getData)

This results in the following plot: There are however some issues:

1) I don't want to have points, just lines. Without the layer_points, there are no tooltips...

2) The variable time is a date but shows up as an integer. How can I fix the ugly number?

Thank you very much.

Edit

The field of the tooltip can be formated to date if it is coerced to a char before calling the ggvis function but it introduces other issues. For example, the x-axis does not shown properly.


回答1:


I found a solution for both:

#Create Data
library(ggvis)
set.seed(123)
tdat <- data.frame(group = rep(LETTERS[1:2], each = 50),
                   time = rep(seq(from = as.Date("2010-01-01"), length.out = 50, by = "day"), 2),
                   val = c(cumsum(rnorm(50)) + 100,
                           cumsum(rnorm(50)) + 100))

For the getData function a bit of reverse engineering made me find the solution. Apparently if you divide the numeric date by 86400000 and add the origin of 1970-01-01 makes it work.

# ggvis Code
# Function for the tooltip
getData <- function(dat){

  paste(paste("Time:", as.Date(dat$time/86400000, origin='1970-01-01') ),
        paste("Group:", as.character(dat$group)),
        paste("Value:", dat$val),
        sep = "<br />")
}

As for the points, just setting the opacity to zero makes it work:

# Visualisation
tdat %>% ggvis(~time, ~val, stroke = ~group) %>% layer_lines(strokeWidth := 1) %>%
  layer_points(size = 1, fill = ~group, opacity := 0) %>% add_tooltip(getData)

Ouput:

Sorry for the bad output but this was the best I could get via a print screen.



来源:https://stackoverflow.com/questions/32583129/ggvis-multiple-lines-with-tooltips

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