我想显示一些信息,当用户点击一个plotly图的图例。例如在下面的代码,如果在“DRAT”名用户点击的传奇unshow这些数据,我想打印一个短信说“DRAT和QseC的选择”。
我看到这个计算器的帖子:R shiny and plotly getting legend click events但它与标签的作品。就我而言,标签是不是可用的参数。我已经测试了不同的plotly事件,但没有返回,当我点击传说的任何信息(见下面的代码)。
有没有一种方法能有这个信息?
谢谢
library(plotly)
library(shiny)
ui <- fluidPage(
plotlyOutput("plot"),
verbatimTextOutput("hover"),
verbatimTextOutput("click"),
verbatimTextOutput("brush"),
verbatimTextOutput("zoom")
)
server <- function(input, output, session) {
output$plot <- renderPlotly({
p <- plot_ly()
for(name in c("drat", "wt", "qsec"))
{
p = add_markers(p, x = as.numeric(mtcars$cyl), y = as.numeric(mtcars[[name]]), name = name)
}
p
})
output$hover <- renderPrint({
d <- event_data("plotly_hover")
if (is.null(d)) "Hover events appear here (unhover to clear)" else d
})
output$click <- renderPrint({
d <- event_data("plotly_click")
if (is.null(d)) "Click events appear here (double-click to clear)" else d
})
output$brush <- renderPrint({
d <- event_data("plotly_selected")
if (is.null(d)) "Click and drag events (i.e., select/lasso) appear here (double-click to clear)" else d
})
output$zoom <- renderPrint({
d <- event_data("plotly_relayout")
if (is.null(d)) "Relayout (i.e., zoom) events appear here" else d
})
}
shinyApp(ui, server)
library(plotly)
library(shiny)
library(htmlwidgets)
js <- c(
"function(el, x){",
" el.on('plotly_legendclick', function(evtData) {",
" Shiny.setInputValue('trace', evtData.data[evtData.curveNumber].name);",
" });",
"}")
ui <- fluidPage(
plotlyOutput("plot"),
verbatimTextOutput("legendItem")
)
server <- function(input, output, session) {
output$plot <- renderPlotly({
p <- plot_ly()
for(name in c("drat", "wt", "qsec"))
{
p = add_markers(p, x = as.numeric(mtcars$cyl), y = as.numeric(mtcars[[name]]), name = name)
}
p %>% onRender(js)
})
output$legendItem <- renderPrint({
d <- input$trace
if (is.null(d)) "Clicked item appear here" else d
})
}
shinyApp(ui, server)