0

I am trying to recreate the example called "Create annotation on click event" at (https://plot.ly/javascript/click-events/) in RStudio. In my attempt, I came up with the following tailored code for use in RStudio:

library(plotly)

trace_0 <- rnorm(100, mean = 5)
trace_1 <- rnorm(100, mean = 0)
trace_2 <- rnorm(100, mean = -5)
x <- c(1:100)

data <- data.frame(x, trace_0, trace_1, trace_2)

data %>% plot_ly(x = ~x, y = ~trace_0, name = 'trace 0', type = 'scatter', mode = 'lines') %>%
  layout(hovermode = "closest", showlegend = FALSE) %>%
  onRender("
           function(el, x) {
           var myGraph = document.getElementById(el.id);
           el.on('plotly_click', function(e) {
            var pts = '';
            for(var i=0; i < e.points.length; i++){
              annotate_text = 'x = '+e.points[i].x +
              'y = '+e.points[i].y.toPrecision(4);

              annotation = {
                text: annotate_text,
                x: e.points[i].x,
                y: parseFloat(e.points[i].y.toPrecision(4))
              }

              annotations = self.layout.annotations || [];
              annotations.push(annotation);
              Plotly.relayout('myGraph',{annotations: annotations})
            }
           }
          ")

Upon running my code in RStudio, I do see the interactive plotly image in the plot viewer, but I am unable to create any of the annotations that should appear when I interact with it (like in the online tutorial).

My question is two part.

1) I am trying to figure out how to troubleshoot and solve this particular problem.

2) I am trying to better understand in general how to troubleshoot the Javascript code that is embedded in the onRender() function of htmlwidgets. Is it possible to run this code line by line and say create the variable "pts" and see how it updates as it goes through the loop and see how the annotation variable changes when I click on certain points? Without being able to troubleshoot this way, I am worried it will be difficult to tailor onRender() for interactive plots I am developing. I believe that Javascript can be troubleshooted in Web Browsers, but it is unclear to me how to do so with this particular Javascript code (embedded in R).

Thank you for any advice!

EDIT:

Taking into account some of the advice from @bethanyP, I tried the following:

1) Made a .Rmd file of the following format:

---
title: "annotePlot"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r makePlot}
########### Ex: Change scatterplot opacity ###########
# Supposed to keep clicked point black, but it turns all gray
set.seed(1)
(Rest of code in here)
````

2) Ran rmarkdown::render("annotate.Rmd") which made .html file

3) Opened the URL (file:///Users/user1835/annotate.html) in Chrome

4) Noticed that the interactive plot had already been created at the bottom of the webpage. I can interact with it (if I click on a point, all points turn from black to gray)

5) Clicked on icon in top right of Chrome --> More Tools --> Developer Tools

At this point, I am stuck unsure how to use the available tools to troubleshoot the issue. I have what looks like the following in my Chrome browser (see image):

Browser

When I click on a point in the graph, I see the tag highlight. However, I am unable to see more about individual objects (such as e). I am unsure how I would even know that the object e has a sub-object called points. Furthermore, I am uncertain how to see what objects update (and it what way) when a user clicks on a point. Is it possible for me to see such things? I believe I would need to understand the objects and understand how they change when interacted with.

Any advice is greatly appreciated!

2 Answers2

2

To troubleshoot this kind of code, I generally view the plot directly into a browser. If you are using RStudio, you can click on the "Show in new window" button on top of the viewer to open it directly in a browser.

Otherwise, you can also set the viewer option to NULL in your code and the plot will directly open in your browser. To do that, you can add:

default_viewer = getOption("viewer")
options("viewer"=NULL)

before your plotto save the current viewer option and set it to null, and

options("viewer"=default_viewer)

after your plot to reset it to the default.

In your onRender function, you can use console.log to print custom messages to the javascript console when the code is run. You can access this console in the Chrome developer tools if that's what you are using.

Your code itself has a few issues. First the parenthesis are not all closed. Then instead of 'myGraph' on the last line, it should be the id of the div in which the plot is made, so in this case el.id.

Here's a working function:

onRender("
           function(el, x) {
           var myGraph = document.getElementById(el.id);
           el.on('plotly_click', function(e) {
            var pts = '';
            for(var i=0; i < e.points.length; i++){
            var annotate_text = 'x = '+e.points[i].x +
            'y = '+e.points[i].y.toPrecision(4);

             var annotation = {
            text: annotate_text,
            x: e.points[i].x,
             y: parseFloat(e.points[i].y.toPrecision(4))
             }

            annotations = el.layout.annotations || [];
            annotations.push(annotation);
            Plotly.relayout(el.id,{annotations: annotations})
            }
           })}
           ") 
NicE
  • 21,165
  • 3
  • 51
  • 68
0

It may seem convoluted, but the best tools I have to work with Javascript and R are in chrome's inspector, so I export the graphics as webpages. You can actually edit and rerun code that way to figure out what the Javascript issues are.

Also, I find that rStudio viewer is not 100% happy to promote JS objects. I have some issues with my Leaflet maps working in the viewer console from time-to-time. Some features just fail in rStudio (not the compiled version, it is usually correct, but the console version may not be).

My solution has been to create an rMarkdown document and designate its output to html. Then plot, map and graph away. Knit the document and test it outside of R & rStudio.

When you use knitR to run the file, it saves a web version of your document. Open that in Chrome and see what is happening in there. That is, if you can get R to render it into an HTML page without errors...

sconfluentus
  • 4,693
  • 1
  • 21
  • 40
  • Thank you for your help! I believe I was able to follow some of your advice and am excited to have it working in Chrome. I added an edit because I am still a bit stuck on *how* to make use of the Chrome tools. –  Feb 19 '17 at 15:58