|
| 1 | +library(plotly) |
| 2 | +library(htmlwidgets) |
| 3 | + |
| 4 | +mtcars$url <- paste0( |
| 5 | + "http://google.com/#q=", |
| 6 | + rownames(mtcars) |
| 7 | +) |
| 8 | + |
| 9 | +p <- plot_ly(mtcars, x = ~wt, y = ~mpg) %>% |
| 10 | + add_markers(customdata = ~url) |
| 11 | + |
| 12 | +# open google search (on click) |
| 13 | +onRender(p, " |
| 14 | + function(el, x) { |
| 15 | + el.on('plotly_click', function(d) { |
| 16 | + var url = d.points[0].customdata; |
| 17 | + window.open(url); |
| 18 | + }); |
| 19 | + } |
| 20 | +") |
| 21 | + |
| 22 | +# annotate graph (on click) |
| 23 | +onRender(p, " |
| 24 | + function(el, x) { |
| 25 | + el.on('plotly_click', function(d) { |
| 26 | + var ann = { |
| 27 | + text: d.points[0].customdata, |
| 28 | + x: 0, |
| 29 | + y: 0, |
| 30 | + xref: 'paper', |
| 31 | + yref: 'paper', |
| 32 | + yshift: -40, |
| 33 | + showarrow: false |
| 34 | + } |
| 35 | + Plotly.relayout(el.id, {annotations: [ann]}) |
| 36 | + }); |
| 37 | + } |
| 38 | +") |
| 39 | + |
| 40 | +# annotate on hover |
| 41 | +onRender(p, " |
| 42 | + function(el, x) { |
| 43 | + el.on('plotly_hover', function(d) { |
| 44 | + var ann = { |
| 45 | + text: d.points[0].customdata, |
| 46 | + x: 0, |
| 47 | + y: 0, |
| 48 | + xref: 'paper', |
| 49 | + yref: 'paper', |
| 50 | + yshift: -40, |
| 51 | + showarrow: false |
| 52 | + } |
| 53 | + Plotly.relayout(el.id, {annotations: [ann]}) |
| 54 | + }); |
| 55 | + } |
| 56 | +") |
| 57 | + |
| 58 | +# combine highlight() api with custom javascript |
| 59 | +mtcars %>% |
| 60 | + highlight_unit() %>% |
| 61 | + plot_ly(x = ~wt, y = ~mpg, customdata = ~url) %>% |
| 62 | + highlight(color = "red") %>% |
| 63 | + onRender(" |
| 64 | + function(el, x) { |
| 65 | + el.on('plotly_click', function(d) { |
| 66 | + var ann = { |
| 67 | + text: d.points[0].customdata, |
| 68 | + x: 0, |
| 69 | + y: 0, |
| 70 | + xref: 'paper', |
| 71 | + yref: 'paper', |
| 72 | + yshift: -40, |
| 73 | + showarrow: false |
| 74 | + } |
| 75 | + Plotly.relayout(el.id, {annotations: [ann]}) |
| 76 | + }); |
| 77 | + } |
| 78 | + ") |
| 79 | + |
| 80 | +# inspect different plotly.js events via browser console |
| 81 | +# see also https://plot.ly/javascript/plotlyjs-events/ |
| 82 | +onRender(p, " |
| 83 | + function(el, x) { |
| 84 | + el.on('plotly_hover', function(d) { |
| 85 | + console.log('hover', d) |
| 86 | + }); |
| 87 | + el.on('plotly_click', function(d) { |
| 88 | + console.log('click', d) |
| 89 | + }); |
| 90 | + el.on('plotly_selected', function(d) { |
| 91 | + console.log('selected', d) |
| 92 | + }); |
| 93 | + el.on('plotly_relayout', function(d) { |
| 94 | + console.log('relayout', d) |
| 95 | + }); |
| 96 | + }" |
| 97 | +) |
| 98 | + |
0 commit comments