2017-01-23 59 views
1

我想在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())。

任何幫助,將不勝感激。

回答

2

您的代碼不起作用,因爲當您使用新顏色繪圖時,它會發送懸停事件以重新初始化顏色。

可以一起使用reactiveValueobserveEvent存儲值時,事件出現:

--- 
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)}) 
``` 
+0

感謝您的快速,簡單和對這點的回答! – user1965813

+0

爲什麼更改'input $ hover'的重新繪圖不會觸發'observeEvent'? (這將意味着,「observeEvent」從簡單的廢票的工作方式不同,豈不?) 答案都可以找到[這裏](https://shiny.rstudio.com/reference/shiny/latest/observeEvent.html) – user1965813