R and plotly interactive dynamically generated graphs are sooooo slow

Hi Plotly Forum!

Ihave the following problem and I hope you can help me:

I use plotly, shiny and RStudio and I want to achieve the following:

  • to have one line plot with some data
  • to dynamically generate histogram of other values while pointing mouse on some point on the first plot

I’ve managed to do so and it is working, but it is working extremely slow! Point somewhere, wait 3 seconds, build histogram, point somewhere else, wait again, generate histogram, and so on. And it only has the very basic features so far. Is there any chance it can be more smooth and quick? Should I try to do it in Python or some other language?

Below is the code. You can download sample data from https://github.com/ymra/dynamic_histogram/blob/master/dji.csv. Also, you have to know that the histogram is generated for 650 observations (starting from the mouse point and going back). The first 650 observations (from 0 to 650) are NA.

Can you advise?


ui <- fluidPage(
  h2("Prices and return rate"),
  h3("move mouse over line line plot"),

server <- function(input, output) {

  # Read and transform data
  alltogether <- data.frame(read.csv(file = "./dji.csv", sep = ",", header = TRUE))

  #change column names to simplify
  colnames(alltogether) <- c("date","returns","prices")

  # Generate statistic magic values
  for (i in 3000:650){
    n = i-649
    alltogether$means[i] <- mean(alltogether$prices[n:i])

  # render 
  output$plot <- renderPlotly({ 

    ay <- list(
      tickfont = list(color = "red"),
      overlaying = "y",
      side = "right",
      range = c(-0.14,0.3)
    p <- plot_ly() %>%
      add_lines(data = alltogether, x = ~date, y = ~prices, name = "price", text = ~paste("mean: ", alltogether$means)) %>%
      add_lines(data = alltogether, x = ~date, y = ~returns, name = "return", yaxis = "y2") %>%
      layout(title = "Price and return rate", yaxis2 = ay)

  output$plot2 <- renderPlotly({
    d <- event_data("plotly_hover")
    b <- d$pointNumber[1]
    e <- b+649
    rangy <- (alltogether$returns[b:e])
    if (b > 649){ 
      plot_ly(x=rangy,type = "histogram")


I share your complaint. R code to generate plotly is very quick but before it shows in shiny in my case it takes a very long time (many seconds)