penguin
penguin

Reputation: 1376

Movable lines in Plotly R

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)

Upvotes: 2

Views: 1761

Answers (1)

Machteld Varewyck
Machteld Varewyck

Reputation: 51

(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!

Upvotes: 3

Related Questions