我的问题很简单,但我似乎找不到解决方案。
鉴于下面的模拟数据框,我希望在单击使用plot_ly生成的条形图中的一个条形后渲染一个表格。
library(shiny)
library(plotly)
library(DT)
data <- data.frame(c(1,2,3,4,5,6,7,8,9,10),
c(74, 100,74,16,16,99,16, 40, 16, 16),
c(1, 10,1,8,6,2,6,4,6,6),
c(0,0,0,112,0,0,0,0,96,16))
colnames(data) <- c("Deliv", "Pr", "Pro", "Disc")
shinyApp(
ui = fluidPage(
plotlyOutput("plot"),
DT::dataTableOutput('tb')),
server = function(input, output) {
output$plot <- renderPlotly({
plot_ly(data,
x = ~Deliv,
y = ~Pr,
type = "bar",
source = "click")})
output$tb <- renderDataTable({
event.data <- event_data("plotly_click", source = "click")
if(is.null(event.data) == T) return("NULL") else event.data
})
}
)
渲染的表格可能为我提供了我应该期望的内容,但我需要其中的更多信息,例如用于绘图的原始数据框中的其余变量。
有什么想法吗?我将非常感激。
ps。我知道这与 ggplot 配合得很好,但我对plotly很感兴趣。
最佳答案
假设xou想要输出有关这一点的过滤数据,我可以提供这个解决方案。 event.data
为您提供 x
和 y
坐标。您可以使用这些来过滤数据点,因为您将 x
定义为 Deliv
,将 y
定义为 Pr
。
library(shiny)
library(plotly)
library(DT)
data <- data.frame(c(1,2,3,4,5,6,7,8,9,10),
c(74, 100,74,16,16,99,16, 40, 16, 16),
c(1, 10,1,8,6,2,6,4,6,6),
c(0,0,0,112,0,0,0,0,96,16))
colnames(data) <- c("Deliv", "Pr", "Pro", "Disc")
shinyApp(
ui = fluidPage(
plotlyOutput("plot"),
DT::dataTableOutput('tb')),
server = function(input, output) {
output$plot <- renderPlotly({
plot_ly(data,
x = ~Deliv,
y = ~Pr,
type = "bar",
source = "click")})
output$tb <- renderDataTable({
event.data <- event_data("plotly_click", source = "click")
####### SOLUTION HERE
# corrected NULL as NULL Value
if(is.null(event.data) == T) return(NULL)
# Filter result via Data
res <- data[event.data$x==data$Deliv & event.data$y==data$Pr,]
return(res)
######## SOLUTION END
})
}
)
关于r - 有没有办法在plotly_click之后渲染更详细的表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69908943/