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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
---
title: "Using plotly with onRender"
author: "Carson Sievert"
date: "`r Sys.Date()`"
output: html_document
---
```{r, message = FALSE, warning = FALSE}
library(plotly)
library(htmlwidgets)
set.seed(1056)
nPatients <- 50
nVisits <- 10
df <- data.frame(
fev1_perc = rnorm(n = nPatients * nVisits, mean = 100, sd = 10),
uin = rep(seq(nPatients), each = nVisits),
visit = rep(seq(nVisits), nPatients)
)
c1 <- list(color = toRGB("steelblue", 0.5))
c2 <- list(color = toRGB("orange", 0.5))
# The color mapping is used only to generate multiple traces
# (which makes it easier to highlight lines on the JS side)
df %>%
plot_ly(
x = ~visit, y = ~fev1_perc, split = ~factor(uin), marker = c1, line = c2
) %>%
layout(hovermode = "closest", showlegend = FALSE) %>%
onRender('
function(el, x) {
var graphDiv = document.getElementById(el.id);
// reduce the opacity of every trace except for the hover one
el.on("plotly_hover", function(e) {
var traces = [];
for (var i = 0; i < x.data.length; i++) {
if (i !== e.points[0].curveNumber) traces.push(i);
}
Plotly.restyle(graphDiv, "opacity", 0.2, traces);
})
el.on("plotly_unhover", function(e) {
var traces = [];
for (var i = 0; i < x.data.length; i++) traces.push(i);
Plotly.restyle(graphDiv, "opacity", 1, traces);
})
}
')
```
|