Open Link on Datapoint Click with Plotly in R Shiny

☆樱花仙子☆ 提交于 2021-02-18 19:01:19

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/56084819/open-link-on-datapoint-click-with-plotly-in-r-shiny

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!