File: custom-javascript.R

package info (click to toggle)
r-cran-plotly 4.10.4%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 30,636 kB
  • sloc: javascript: 195,272; sh: 24; makefile: 6
file content (98 lines) | stat: -rw-r--r-- 2,036 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
library(plotly)
library(htmlwidgets)

mtcars$url <- paste0(
  "http://google.com/#q=", 
  rownames(mtcars)
)

p <- plot_ly(mtcars, x = ~wt, y = ~mpg) %>%
  add_markers(customdata = ~url)

# open google search (on click)
onRender(p, "
  function(el, x) {
    el.on('plotly_click', function(d) {
      var url = d.points[0].customdata;
      window.open(url);
    });
  }
")

# annotate graph (on click)
onRender(p, "
  function(el, x) {
    el.on('plotly_click', function(d) {
      var ann = {
        text: d.points[0].customdata,
        x: 0,
        y: 0,
        xref: 'paper',
        yref: 'paper',
        yshift: -40,
        showarrow: false
      }
      Plotly.relayout(el.id, {annotations: [ann]})
    });
  }
")

# annotate on hover
onRender(p, "
  function(el, x) {
    el.on('plotly_hover', function(d) {
      var ann = {
        text: d.points[0].customdata,
        x: 0,
        y: 0,
        xref: 'paper',
        yref: 'paper',
        yshift: -40,
        showarrow: false
      }
      Plotly.relayout(el.id, {annotations: [ann]})
    });
  }
")

# combine highlight() api with custom javascript
mtcars %>%
  highlight_key() %>%
  plot_ly(x = ~wt, y = ~mpg, customdata = ~url) %>%
  highlight(color = "red") %>%
  onRender("
  function(el, x) {
    el.on('plotly_click', function(d) {
      var ann = {
        text: d.points[0].customdata,
        x: 0,
        y: 0,
        xref: 'paper',
        yref: 'paper',
        yshift: -40,
        showarrow: false
      }
      Plotly.relayout(el.id, {annotations: [ann]})
    });
  }
  ")

# inspect different plotly.js events via browser console
# see also plotly.com/javascript/plotlyjs-events/
onRender(p, "
  function(el, x) {
    el.on('plotly_hover', function(d) {
      console.log('hover', d)
    });
    el.on('plotly_click', function(d) {
      console.log('click', d)
    });
    el.on('plotly_selected', function(d) {
      console.log('selected', d)
    });
    el.on('plotly_relayout', function(d) {
      console.log('relayout', d)
    });
  }"
)