Skip to content

Commit eb12338

Browse files
committed
add shiny example of dragging markers (for interactive lm)
1 parent e40621a commit eb12338

File tree

1 file changed

+69
-0
lines changed
  • inst/examples/shiny/drag_markers

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
library(plotly)
2+
library(purrr)
3+
library(shiny)
4+
5+
ui <- fluidPage(
6+
fluidRow(
7+
column(5, verbatimTextOutput("summary")),
8+
column(7, plotlyOutput("p"))
9+
)
10+
)
11+
12+
server <- function(input, output, session) {
13+
14+
rv <- reactiveValues(
15+
x = mtcars$mpg,
16+
y = mtcars$wt
17+
)
18+
grid <- reactive({
19+
data.frame(x = seq(min(rv$x), max(rv$x), length = 10))
20+
})
21+
model <- reactive({
22+
d <- data.frame(x = rv$x, y = rv$y)
23+
lm(y ~ x, d)
24+
})
25+
26+
output$p <- renderPlotly({
27+
# creates a list of circle shapes from x/y data
28+
circles <- map2(rv$x, rv$y,
29+
~list(
30+
type = "circle",
31+
# anchor circles at (mpg, wt)
32+
xanchor = .x,
33+
yanchor = .y,
34+
# give each circle a 2 pixel diameter
35+
x0 = -4, x1 = 4,
36+
y0 = -4, y1 = 4,
37+
xsizemode = "pixel",
38+
ysizemode = "pixel",
39+
# other visual properties
40+
fillcolor = "blue",
41+
line = list(color = "transparent")
42+
)
43+
)
44+
45+
# plot the shapes and fitted line
46+
plot_ly() %>%
47+
add_lines(x = grid()$x, y = predict(model(), grid()), color = I("red")) %>%
48+
layout(shapes = circles) %>%
49+
config(edits = list(shapePosition = TRUE))
50+
})
51+
52+
output$summary <- renderPrint({a
53+
summary(model())
54+
})
55+
56+
# update x/y reactive values in response to changes in shape anchors
57+
observe({
58+
ed <- event_data("plotly_relayout")
59+
shape_anchors <- ed[grepl("^shapes.*anchor$", names(ed))]
60+
if (length(shape_anchors) != 2) return()
61+
row_index <- unique(readr::parse_number(names(shape_anchors)) + 1)
62+
pts <- as.numeric(shape_anchors)
63+
rv$x[row_index] <- pts[1]
64+
rv$y[row_index] <- pts[2]
65+
})
66+
67+
}
68+
69+
shinyApp(ui, server)

0 commit comments

Comments
 (0)