-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtest-dt-plot.R
70 lines (57 loc) · 1.9 KB
/
test-dt-plot.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
library(shiny)
library(DT)
library(plotly)
library(crosstalk)
m <- mtcars %>%
tibble::rownames_to_column()
ui <- fluidPage(
h1("Plotly & DT", align = "center"),
plotlyOutput("x2"),
DT::dataTableOutput("x1"),
fluidRow(
p(class = 'text-center', downloadButton('x3', 'Download Filtered Data'))
)
)
server <- function(input, output) {
d <- SharedData$new(m, ~rowname)
# highlight selected rows in the scatterplot
output$x2 <- renderPlotly({
s <- input$x1_rows_selected
if (!length(s)) {
p <- d %>%
plot_ly(x = ~mpg, y = ~disp, mode = "markers", color = I('black'), name = 'Unfiltered') %>%
layout(showlegend = T) %>%
highlight("plotly_selected", color = I('red'), selected = attrs_selected(name = 'Filtered'))
} else if (length(s)) {
pp <- m %>%
plot_ly() %>%
add_trace(x = ~mpg, y = ~disp, mode = "markers", color = I('black'), name = 'Unfiltered') %>%
layout(showlegend = T)
# selected data
pp <- add_trace(pp, data = m[s, , drop = F], x = ~mpg, y = ~disp, mode = "markers",
color = I('red'), name = 'Filtered')
}
})
# highlight selected rows in the table
output$x1 <- DT::renderDataTable({
m2 <- m[d$selection(),]
dt <- DT::datatable(m)
if (NROW(m2) == 0) {
dt
} else {
DT::formatStyle(dt, "rowname", target = "row",
color = DT::styleEqual(m2$rowname, rep("white", length(m2$rowname))),
backgroundColor = DT::styleEqual(m2$rowname, rep("black", length(m2$rowname))))
}
})
# download the filtered data
output$x3 = downloadHandler('mtcars-filtered.csv', content = function(file) {
s <- input$x1_rows_selected
if (length(s)) {
write.csv(m[s, , drop = FALSE], file)
} else if (!length(s)) {
write.csv(m[d$selection(),], file)
}
})
}
shinyApp(ui, server)