Search code examples
rtextformatinteractiveggvis

R ggvis font and parameters of interactive text in scatter plot (hover)


I would like to know if there is a way to modify the characteristics of the text shown on "hover" using ggvis.

I have created a scatter plot based on a template found on internet and modified for my needs.

The script follows:

library(shiny)
library(ggvis)

mydata <- data
mydata$id <- 1:nrow(mydata)  # Add an id column to use ask the key


all_values <- function(x) {
  if(is.null(x)) return(NULL)
  row <- mydata[mydata$id == x$id, ]
  paste0(
        names(row), ": ", format(row), collapse = "\n"
        )
}

# factor Location
mydata %>% ggvis(~a, ~b, key := ~id) %>%
  layer_points(fill = ~factor(Location)) %>%
  scale_numeric("x", trans = "log", expand=0) %>%
  scale_numeric("y", trans = "log", expand=0) %>%
  add_axis("x", title = "blabla1") %>%
  add_axis("y", title = "blabla2") %>%
  add_tooltip(all_values, "hover")

What I would like to know is basically how to format the text shown interactively on the scatter plot.

Mainly I would like to:

  1. Go on a new line after each parameter it is shown (the command "\n" in collapse and paste0 doesn't seem to work)
  2. How to put in bold for example names(row)

Solution

  • You have to use the appropriate HTML tags in paste0():

    • For new line: collapse = "<br />"
    • For bold: "<b>", names(row), "</b>:"

    Since you didn't provide a reproducible example, here's one with mtcars:

    mtc <- mtcars
    mtc$id <- 1:nrow(mtc)  # Add an id column to use ask the key
    
    all_values <- function(x) {
      if(is.null(x)) return(NULL)
      row <- mtc[mtc$id == x$id, ]
      paste0("<b>", names(row), "</b>:", format(row), collapse = "<br />")
    }
    
    mtc %>% 
      ggvis(x = ~wt, y = ~mpg, key := ~id) %>%
      layer_points() %>%
      add_tooltip(all_values, "hover")
    

    enter image description here