问题
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