【发布时间】:2015-08-12 09:45:52
【问题描述】:
我正在一个闪亮的应用程序中在 ggplot2 中绘制一个条形图。
我想要的是,当鼠标悬停在其中一个条上时,该条会突出显示(可能由更粗的轮廓),当我单击(或双击)该条时,相应的 x 值变为可用用作textOutput 的输入。
我试图在闪亮的文档中找到示例,但主要是关于从指针位置返回 x、y 值。有没有可以作为起点的例子?
【问题讨论】:
我正在一个闪亮的应用程序中在 ggplot2 中绘制一个条形图。
我想要的是,当鼠标悬停在其中一个条上时,该条会突出显示(可能由更粗的轮廓),当我单击(或双击)该条时,相应的 x 值变为可用用作textOutput 的输入。
我试图在闪亮的文档中找到示例,但主要是关于从指针位置返回 x、y 值。有没有可以作为起点的例子?
【问题讨论】:
我有同样的问题并找到了这篇文章。我意识到这个问题已经很老了,但也许有人仍然对解决方案感兴趣。
挑战:
所以你没有可以监听的单独的 html 元素。
解决方案:
但是在闪亮的 ggplots 中有一个有趣的功能。如果在绘图中添加点击监听器,点击事件的$x 变量会缩放到图片中元素的数量。所以如果你添加一个onlick 监听器,round($click$x) 将等于被点击的元素。
在此处查看示例: https://shiny.rstudio.com/articles/plot-interaction-advanced.html
可重现的例子:
我实现了一个带有文本框和突出显示的解决方案,突出显示部分来自Highlight a single "bar" in ggplot。
解决方案如下:
样本数据:
letters <- data.frame(
word = c("First", "Second", "Third"),
num = c(2, 3, 4),
stringsAsFactors = FALSE
)
应用程序:
library(shiny)
library(ggplot2)
ui <- fluidPage(
fluidRow(
column(6,
plotOutput("plot1", click = "plot1_click")
),
column(5,
uiOutput("text")
)
)
)
server <- function(input, output) {
global <- reactiveValues(toHighlight = rep(FALSE, length(letters$word)),
selectedBar = NULL)
observeEvent(eventExpr = input$plot1_click, {
global$selectedBar <- letters$word[round(input$plot1_click$x)]
global$toHighlight <- letters$word %in% global$selectedBar
})
output$plot1 <- renderPlot({
ggplot(data = letters, aes(x = word, y = num, fill = ifelse(global$toHighlight,
yes = "yes", no = "no"))) +
geom_bar(stat="identity") +
scale_fill_manual(values = c("yes" = "blue", "no" = "grey" ), guide = FALSE )
})
output$text <- renderUI({
req(global$selectedBar)
textInput(inputId = "label", label = "selected text:", value = global$selectedBar)
})
}
shinyApp(ui, server)
【讨论】: