1

I have a scatter plot with numeric values on both the axis. I want to add two draggable lines, one horizontal and one vertical. Also, I would like to change the color of points in the top-right quadrant formed by the two lines. I could not find any way to do this in R.

My question is similar to Horizontal/Vertical Line in plotly

Two things I want to add is

  1. Ability to drag vertical and horizontal lines

  2. Return values on which the two lines intersect the x and y axis, so that I can use those values as an input for another UI.

My code sample

data <- data.frame(y = sample(0:50, 100, replace = TRUE),
                  x = round(runif(100),2)
                  )
plot_ly(data, x = ~x, y = ~y)
penguin
  • 1,267
  • 14
  • 27
  • 1
    this https://plot.ly/r/shiny-coupled-events/ could help – MLavoie Apr 09 '18 at 17:09
  • hey Penguin, have you found a solution yet? I'm thinking to find out how to do this for my shiny app too. would be glad to see a solution! – Mark Oct 05 '18 at 13:46

1 Answers1

2

(1) You can add draggable lines as follows:

plot_ly(data, x = ~x, y = ~y, type = 'scatter') %>%
    layout(shapes = list(
                    #vertical line
                    list(type = "line", x0 = 0.4, x1 = 0.4, 
                            y0 = 0, y1 = 1, yref = "paper"),
                    #horizontal line
                    list(type = "line", x0 = 0, x1 = 1, 
                            y0 = 30, y1 = 30, xref = "paper"))) %>%
    # allow to edit plot by dragging lines
    config(edits = list(shapePosition = TRUE))

Similar to https://stackoverflow.com/a/54777145/5840900

(2) In an interactive environment, you can extract the values of the last dragged line with:

        # Only within reactive shiny context
        newData <- plotly::event_data("plotly_relayout")

Hopefully this is still helpful!