闪亮的应用程序使用plotly 的 postMessage API or 绘图.js,两者都暴露click
, hover
, and zoom
事件。这些事件尚未作为底层闪亮服务器的回调公开,但可以通过自定义 JavaScript 访问它们,您可以在闪亮中为自己提供服务。
以下是点击事件的示例:
ui.R
library(shiny)
library(plotly)
shinyUI(fluidPage(
mainPanel(
plotlyOutput("trendPlot"),
tags$head(tags$script(src="clickhandler.js"))
)
))
server.R
library(shiny)
library(plotly)
x = c(1, 2, 3)
y = c(4, 2, 4)
links = c("https://plot.ly/r/",
"https://plot.ly/r/shiny-tutorial",
"https://plot.ly/r/click-events")
df = data.frame(x, y, links)
shinyServer(function(input, output) {
output$trendPlot <- renderPlotly({
# Create a ggplot
g = ggplot(data=df, aes(x = x, y = y)) + geom_point()
# Serialize as Plotly's graph universal format
p = plotly_build(g)
# Add a new key, links, that JS will access on click events
p$data[[1]]$links = links
p
# Alternatively, use Plotly's native syntax. More here: https://plot.ly/r
# plot_ly(df, x=x,y=y,links=links)
})
})
www/clickhandler.js
$(document).ready(function(){
// boiler plate postMessage plotly code (https://github.com/plotly/postMessage-API)
var plot = document.getElementById('trendPlot').contentWindow;
pinger = setInterval(function(){
plot.postMessage({task: 'ping'}, 'https://plot.ly')
}, 100);
var clickResponse = function(e) {
plot = document.getElementById('trendPlot').contentWindow;
var message = e.data;
console.log( 'New message from chart', message );
if(message.pong) {
// tell the embedded plot that you want to listen to click events
clearInterval(pinger);
plot.postMessage({
task: 'listen', events: ['click']}, 'https://plot.ly');
plot.postMessage({
task: 'relayout',
'update': {hovermode: 'closest'},
},
'https://plot.ly');
}
else if(message.type === 'click') {
var curveNumber = message['points'][0]['curveNumber'],
pointNumber = message['points'][0]['pointNumber'];
var link;
var traces = message.points[0].data;
if(traces !== null && typeof traces === 'object') {
link = traces.links[pointNumber];
} else {
link = traces[curveNumber].links[pointNumber];
}
console.log(link);
var win = window.open(link, '_blank');
win.focus();
}
};
window.addEventListener("message", clickResponse, false);
});
以下是一些可能有用的资源:
- 使用 R 在 javascript 中向绘图添加自定义交互性
- 尤其在 JavaScript 中绑定点击事件
- 开始使用闪亮和情节
-
Plotly postMessage API用于向托管绘图添加自定义交互性