1

I'm working with Plotly in R to develop a Shiny web app. I've put together an interactive scatterplot and configured the hovertext with the information I want.

My implementation is as follows:

plot_ly(data=partition, 
          x=~get(x), 
          y=~get(y), 
          color=~SenderS,
          colors="Set1",
          text=~paste("Link(s): <a href='", partition$Link,"'>", partition$Link, "</a>",
                      "<br>Date: ", partition$Date,
                      "<br>Parties: ", partition$SenderS, " to ", partition$Target,
                      "<br>", x_og, ": ", partition[,x],
                      "<br>", y_og, ": ", partition[,y])
          )%>%
    layout(title=~paste(x_og, " vs. ", y_og, 
                        "<br>R=", cor(partition[,x], partition[,y])),
           xaxis=list(
             title=x_og
           ),
           yaxis=list(
             title=y_og
           ))

In the popup, I have a link to which I would like the user to be able to navigate. Unfortunately, as soon as the user hovers over the current popup, it disappears as they are no longer hovering over the point.

Is there a way to configure Plotly hovertext such that my user would be able to click the link? Or, perhaps, can I make clicking a point in the scatterplot open the link?

LIAM M
  • 23
  • 4
  • 2
    Please see [this](https://plotly-r.com/supplying-custom-data.html). – ismirsehregal Mar 22 '22 at 08:50
  • Does this answer your question? [Open hyperlink on click on an ggplot/plotly chart](https://stackoverflow.com/questions/49711131/open-hyperlink-on-click-on-an-ggplot-plotly-chart) – ismirsehregal Apr 11 '22 at 11:48
  • @ismirsehregal the first link is really helpful, but I notice the statement "the JavaScript that powers Figure 21.3...would need to be adapted for 3D charts types". Do you know anything about that? – rasenior Jun 23 '22 at 14:58

1 Answers1

2

Here is a scatterplot with points that open a link when they are clicked:

library(plotly)
library(htmlwidgets) # to use the 'onRender' function

dat <- iris[1:2,]
urls <- c("http://google.com", "https://stackoverflow.com")

p <- plot_ly(dat, type = "scatter", mode = "markers",
             x = ~Sepal.Width, y = ~Sepal.Length, 
             customdata = urls)

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);
  });
}"

p %>% onRender(js)

enter image description here

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225