作者:工商领域LW | 来源:互联网 | 2023-09-14 17:19
Ihavebeenlookingaroundforawaytodrawaverticallinealongthex-axiswhenhoveringoverpoi
I have been looking around for a way to draw a vertical line along the x-axis when hovering over points in a plot using R. It does not really matter which package it is, whether it is plotly, ggvis, rCharts, googleVis or any other for that matter, but I would rather use one of the these mentioned ones if possible.
我一直四处寻找一种方法来画一条垂直线沿着x轴在悬停点阴谋使用r .哪个包并不重要,无论是情节,ggvis,rCharts,googleVis或其他,但我宁愿用这些提到的如果可能的话。
Here is an example of what I would like to have.
这是我想要的一个例子。
![](https://www.#.com/go/aHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9NQWJPTS5wbmc=)
3 个解决方案
0
Here's a partial answer. I can't quite get it to work, but maybe someone will see something obvious. I've used ggplot2
instead of ggvis
for the geom_vline()
function which creates a vertical line.
这是一个部分的答案。我不能让它正常工作,但也许有人会看到一些显而易见的东西。我用了ggplot2代替了ge_vline()函数,它创建了一条垂直线。
What's working:
On the input$plot_hover
event, we assign the x
coordinate to a variable (h
) and then use that variable as the xintercept
arguement to the geom_vline()
function which draws a vertical line.
在输入$plot_hover事件上,我们将x坐标赋给一个变量(h),然后使用该变量作为对绘制垂直线的geom_vline()函数的xintercept论述。
The problem:
Since this is happening in a reactive environment, on every update h
is flushed, so the line disappears about a second after it first appears.
由于这是在反应性环境中发生的,所以每次更新h时都会刷新,因此第一次出现后大约一秒钟行就会消失。
What I've tried:
I tried to assign h
to a second variable t
in order to keep it between updates. This didn't work, so I created a third variable prev_t
and when there was no input (is.null(input$plot_hover) == TRUE)
, keep t
as prev_t
. This also isn't working but I don't have a ton of time to try out different things.
我试图把h赋给第二个变量t,以便在更新之间保持它。这不起作用,所以我创建了第三个变量prev_t,当没有输入(is.null(输入$plot_hover) == TRUE)时,保持t为prev_t。这也行不通,但我没有太多时间去尝试不同的东西。
Here's the code:
这是代码:
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)
Hopefully that should maybe put you on a different path or help a little. If someone sees something that could fix this problem, please let me know.
希望这能让你走上一条不同的道路或者有所帮助。如果有人看到什么可以解决这个问题,请告诉我。