基于悬停在R光标和Rmarkdown上的点颜色
问题描述:
我想在Rmarkdown文档中创建一个闪亮的情节,其中点的颜色取决于鼠标指针(悬停)。但是,所需的绘图只会出现几分之一秒,直到输入列表的悬停元素再次设置为NULL
。为什么是这样?基于悬停在R光标和Rmarkdown上的点颜色
例子:
---
title: "Untitled"
runtime: shiny
output: html_document
---
```{r,echo=FALSE}
library(ggplot2)
x <- rnorm(100)
y <- rnorm(100)
dfr <- data.frame(x, y)
give_col <- function(){
if(is.null(input$hover$y)){
rep(2, length(x))
}else{
(input$hover$y < dfr$y) + 1
}}
imageOutput("image_id", hover = "hover")
textOutput("text_id")
output$image_id <- renderPlot({
plot(dfr$x, dfr$y, col = factor(give_col()))
# plot(dfr$x, dfr$y) # Without col the give_col() element remains
# as can be seen in the output text
})
output$text_id <- reactive({paste(give_col())})
```
如果去掉剧情的颜色部分,文本输出行为与预期相同,所以我想它必须与绘制本身(同样的东西pch
,而不是col
或而不是plot()
)。
任何帮助,将不胜感激。
答
您的代码不起作用,因为当您使用新颜色绘图时,它会发送悬停事件以重新初始化颜色。
可以一起使用reactiveValue
与observeEvent
存储值时,事件出现:
---
title: "Untitled"
runtime: shiny
output: html_document
---
```{r,echo=FALSE}
library(ggplot2)
x <- rnorm(100)
y <- rnorm(100)
dfr <- data.frame(x, y)
give <- reactiveValues(col=rep(2, length(x)))
observeEvent(input$hover,{give$col <- (input$hover$y < dfr$y) + 1})
imageOutput("image_id", hover = "hover")
textOutput("text_id")
output$image_id <- renderPlot({
plot(dfr$x, dfr$y, col = factor(give$col))
# plot(dfr$x, dfr$y) # Without col the give_col() element remains
# as can be seen in the output text
})
output$text_id <- reactive({paste(give$col)})
```
感谢您的快速,简单和对这点的回答! – user1965813
为什么更改'input $ hover'的重新绘图不会触发'observeEvent'? (这将意味着,“observeEvent”从简单的废票的工作方式不同,岂不?) 答案都可以找到[这里](https://shiny.rstudio.com/reference/shiny/latest/observeEvent.html) – user1965813