【问题标题】:Change limits for a plot on a click in another plot in R在 R 中的另一个绘图中单击更改绘图的限制
【发布时间】:2019-02-09 13:50:03
【问题描述】:

我需要显示两个图。第一个图是主散点图。每次单击第一个图中的一个点时,必须更改第二个图。所以我需要类似于https://davidgohel.github.io/ggiraph/index.html图片的行为

更准确地说,第一个图的每个点都必须与第二个图的 x 限制相关联。

我找到了对应的例子How to display many points from plotly_click in R Shiny? 并进行了相应的修改

library(ggplot2)
library(plotly)
library(shiny)

ui <- fluidPage(
  plotlyOutput("plot1"),
  plotlyOutput("plot2")
)

range2=1000000
p1x=runif(10)
p1y=runif(10)
p1t=runif(10)*range2

times=seq(1,range2)
#ys=cumsum(rnorm(range2)/sqrt(range2))
ys=runif(range2)


plot2xlim=c(1000,2000)
p2 <- plot_ly()
p2 <- add_trace(p2, x = times, y = ys, type = "scattergl", mode = "lines",
                line = list(width = 1, color = "blue"))

server <- function(input, output, session) {
  # make plotly plot
  output$plot1 <- renderPlotly({
    g <- ggplot()+geom_point(aes(x=p1x,y=p1y))
    ggplotly(g)
  })
  output$plot2 <- renderPlotly({
    selpoint <- event_data("plotly_click")$pointNumber[1]+1
    plot2xlim <- c(p1t[selpoint]-500,p1t[selpoint]+500)
    p2 <<- layout(p2, xaxis = list(range = plot2xlim), 
                  yaxis = list(range = c(0, 1)))
    p2
  })
}
shinyApp(ui, server)

但是代码运行非常缓慢,因为plot2 是为大量数据而构建的。所以重建它需要很多时间。

有没有办法在每次点击时不重绘第二个图,而只是改变它的 x 限制?

【问题讨论】:

  • 你的例子给出了Error in "plotly"::"ggplotly": object 'p1t' not found
  • @dww 我已经在示例中插入了一个示例生成的数据。

标签: r plot shiny hover


【解决方案1】:

似乎没有办法解决这个问题,因为图表中的每次更改/查询都意味着重新渲染图表,因为每次点击数据点时 Shiny 都会将新数据发送到第二个图表第一张图。

【讨论】:

    【解决方案2】:

    这不是你问的,但是...

    我们可以构建一个带有 x 轴滑块的绘图对象。重绘不是即时的,但它比每次要更改范围时重新加载数据子集要快得多。

    library(ggplot2)
    library(plotly)
    
    range2=1000000
    p1x=runif(10)
    p1y=runif(10)
    p1t=runif(10)*range2
    times=seq(1,range2)
    ys=runif(range2)
    
    # Put the data in a data frame
    data <- data.frame(x = times, y = ys)
    
    # Use ggplotly to take a ggplot object and covert it to plotly
    p2 <- ggplot(data, aes(x = x, y = y)) + geom_line() 
    ggplotly(p2) %>% rangeslider()
    

    【讨论】:

      猜你喜欢
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      • 2017-09-25
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多