ggvis multiple lines with tooltips

2019-07-09 02:56发布

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

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: GGvis 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.

标签: r ggvis
1条回答
叛逆
2楼-- · 2019-07-09 03:25

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:

enter image description here

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

查看更多
登录 后发表回答