0

I have generated a plotly json file that has a scatterplot. I would like to have it open a new browser tab when one of the points is clicked. I have coded the following, in R, to the plot to allow for that:

  js <- "function(el, x) {
  el.on('plotly_click', function(d) {
    var point = d.points[0];
    var url = point.data.customdata[point.pointIndex];
    window.open(url, '_blank');
  });
}"
   fig <- fig %>% config(displayModeBar = F)
    fig <- fig %>% onRender(js)
  
    pj <- plotly_json(p = fig, FALSE)
  
    filename.plot <- paste(barcode,".json",sep="")

However, when the JSON file is rendered the Javascript is not functioning. I am not sure where this is going wrong. Any help would be much appreciated.

Edited Thanks everyone. I was able to fix it by adding the javascript below:

`` $.getJSON(locfilepath, function(data) { Plotly.plot('locgraph', data, []);

                var myPlot = document.getElementById('locgraph');
                
                myPlot.on('plotly_click', function(data){
                    var urlStr = data.points[0].customdata;
                    if(urlStr.length>0){
                       window.open(data.points[0].customdata);
                    }
                });
                
              });

``

Ann
  • 65
  • 8
  • 1
    Can you post a reproducible example? JSON is a data format and `plotly_json()` is a function to inspect this data. It's not clear in your example whether you're viewing the plot object or the JSON data. Also it's unclear what you mean by "the JavaScript is not functioning". What is happening and what do you expect to happen? – SamR Apr 13 '23 at 16:31
  • Thanks Sam. When I print out the `fig`, variable that holds the plotly figure, is printed out `print(fig)` in RStudio the javascript works. So I can click on a point and the browser is opened up. However, when I post my JSON file into my browser, clicking the point does not open a different tab. I am not sure how to attach the JSON file to the question, apologies. – Ann Apr 13 '23 at 17:21
  • `window.open(url, '_blank');` is the standard way to open url in a new tab. Without the _blank the expected behaviour is to open in the current tab. – James Apr 13 '23 at 17:37
  • Thanks James. I had already added the line `window.open(url, '_blank');` to the javascript function but it is still not working. – Ann Apr 13 '23 at 17:47
  • Do you get errors in the browser console when you try to click? – James Apr 13 '23 at 18:45
  • @Ann take a look at how to create a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). You can use a built-in dataset like `iris`. When you say you're opening the json file in the browser that sounds wrong. I would expect `htmlwidgets::saveWidget(fig, "./my_plot.html")` to create an html file that behaves the same way as the RStudio viewer pane. – SamR Apr 13 '23 at 19:01

0 Answers0