R交互式图:悬停时显示垂直线

R interactive plot: show vertical line on hover

我一直在寻找一种方法,在使用 R 将鼠标悬停在绘图中的点上时沿 x 轴绘制一条垂直线。它是哪个包并不重要,无论是 plotly、ggvis、 rCharts、googleVis 或任何其他与此相关的内容,但如果可能的话,我宁愿使用上述提到的其中一个。

这是我想要的示例。

这是部分答案。我不能完全让它工作,但也许有人会看到一些明显的东西。对于创建垂直线的 geom_vline() 函数,我使用 ggplot2 而不是 ggvis

工作原理:

input$plot_hover 事件中,我们将 x 坐标分配给一个变量 (h),然后将该变量用作 xintercept 参数 geom_vline() 绘制垂直线的函数。

问题:

由于这是在反应环境中发生的,每次更新时 h 都会被刷新,所以该行在它第一次出现后大约一秒钟就消失了。

我尝试过的:

我试图将 h 分配给第二个变量 t 以便在更新之间保持它。这没有用,所以我创建了第三个变量 prev_t 并且当没有输入时(is.null(input$plot_hover) == TRUE),将 t 保持为 prev_t。这也不起作用但是我没有太多时间去尝试不同的东西。

代码如下:

library(ggplot2)
library(shiny)

ui <- fluidPage(
    fluidRow(
        column(width = 12,
               plotOutput("plot1", height = 350,hover = hoverOpts(id ="plot_hover"))
        )
    )
)

server <- function(input, output) {
    
   #h <- reactive(input$plot_hover)

   prev_t <- vector()

    output$plot1 <- renderPlot({

        if(!is.null(input$plot_hover)){
            x <- input$plot_hover
            h <- x$x
            t <- h


        # the below isnt quite working
        # I was trying to store t between updates to make the line stay on 
        # the graph until there was a second hover event

        ################### !!! ###################
        } else if(is.null(input$plot_hover)) {
            t <- prev_t
        }

        prev_t <- t
        ################## !!! ####################

        ggplot(mtcars, aes(x=mpg,y=disp,color=factor(cyl))) + geom_point() + geom_vline(xintercept = t)

    })


}
shinyApp(ui, server)

希望这可能会让您走上不同的道路或有所帮助。如果有人看到可以解决这个问题的东西,请告诉我。

按照 Chris 的回答,使其生效

library(ggplot2)
library(shiny)

ui <- fluidPage(
    fluidRow(
        column(width = 12,
               plotOutput("plot1", height = 350,hover = "plot_hover")
        )
    )
)

server <- function(input, output) {
    testPlot <- ggplot(mtcars, aes(x=mpg,y=disp,color=factor(cyl))) + 
        geom_point()

    #start up plot
    output$plot1 <- renderPlot({testPlot})

    # plot after mouse over
    observeEvent(input$plot_hover, {
        x = input$plot_hover$x
        y = input$plot_hover$y
        nearPoint <- nearPoints(mtcars, input$plot_hover, 
                                threshold = 10, maxpoints = 1)
        output$plot1 <- renderPlot({
            if (nrow(nearPoint) == 1) {
                testPlot + 
                    geom_vline(xintercept = nearPoint$mpg) +
                    geom_label(x = x + 1.5, y = y, 
                               label = paste(rownames(nearPoint), "\n", nearPoint$disp))
            } else {
                testPlot
            }
        })
    })
}

shinyApp(ui, server)

部分答案(无法评论)... Plotly 的类型为 "scattergl",它在悬停时绘制一条水平和垂直线。

数据

require(plotly)    

sdate <- as.Date("2015-01-01", format = "%Y-%m-%d")
timedf <- data.frame(Date = seq.Date(sdate, by="month", length.out=12),
                         Amount = runif(12, 0, 100))
# Plotly plot
plot_ly(timedf, x=Date, y=Amount, type="scattergl")

输出