File: ggplotlyr.r

package info (click to toggle)
hmisc 5.2-4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,044 kB
  • sloc: asm: 28,905; f90: 590; ansic: 415; xml: 160; fortran: 75; makefile: 2
file content (29 lines) | stat: -rw-r--r-- 1,268 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
##' Render `plotly` Graphic from a `ggplot2` Object
##'
##' Uses `plotly::ggplotly()` to render a `plotly` graphic with a specified tooltip attribute, removing extraneous text that `ggplotly` puts in hover text when `tooltip='label'`
##' @title ggplotlyr
##' @param ggobject an object produced by `ggplot`
##' @param tooltip attribute specified to `ggplot` to hold hover text
##' @param remove extraneous text to remove from hover text.  Default is set to assume `tooltip='label'` and assumed the user specified `aes(..., label=txt)`.  If you instead specified `aes(..., label=myvar)` use `remove='myvar: '`.
##' @param ... other arguments passed to `ggplotly`
##' @return a `plotly` object
##' @author Frank Harrell
##' @export
##' @md
ggplotlyr <- function(ggobject, tooltip='label', remove='txt: ', ...) {
  
  if (!requireNamespace("plotly"))
    stop("This function requires the 'plotly' package.")
  
# Get around a bug in tooltip construction with ggplotly
# See https://stackoverflow.com/questions/66316337
  g <- plotly::ggplotly(ggobject, tooltip=tooltip, ...)
	if(! length(remove) || remove == '') return(g)
  d <- g$x$data
  for(i in 1 : length(d)) {
    w <- d[[i]]$text
     if(length(w)) d[[i]]$text <- gsub(remove, '', w)
	  }
   g$x$data <- d
   g
	}