Skip to content

Instantly share code, notes, and snippets.

@tomsing1
Last active December 15, 2022 17:46
Show Gist options
  • Select an option

  • Save tomsing1/aaa9871c664ed2b7dfc85de6b0125ff3 to your computer and use it in GitHub Desktop.

Select an option

Save tomsing1/aaa9871c664ed2b7dfc85de6b0125ff3 to your computer and use it in GitHub Desktop.
Combining a plotly graph and an interactive table with crosstalk in R
---
title: "DT, plotly and crosstalk"
---
```{r}
library(plotly)
library(DT)
library(crosstalk)
library(htmltools)
```
```{r}
dataset <- mtcars
dataset$name <- row.names(dataset)
sd <- SharedData$new(dataset)
htmltools::browsable({
htmltools::tagList(
# plot
div(
style = paste0(
"width: 45%;",
"float: left;",
"padding-left: 1rem;",
"padding-top: 3rem;"
),
plot_ly () %>%
add_trace(
name = "", # suppress secondary hover box
type = "scatter",
mode = "markers",
data = sd,
x = ~hp,
y = ~mpg,
text =~name,
hoverinfo = 'text',
hovertemplate = paste(
'<b>%{text}</b>',
'<br><i>hp</i>: %{x}<br>'),
showlegend = FALSE) %>%
add_text(
name = "Names",
data = dataset[dataset$mpg > 25, ],
x = ~hp,
y = ~mpg,
text= ~name,
textposition="top center",
showlegend = TRUE) %>%
highlight(
color = "red",
on = "plotly_click",
off = "plotly_doubleclick") %>%
layout(legend = list(orientation = 'h')),
htmltools::p("Double-click to deselect")
),
# table
div(
style = paste0(
"width: 45%;",
"height: 100%;",
"float: right;",
"padding-right: 1rem;",
"padding-top: 1rem;"
),
datatable(sd, rownames = TRUE, height = 500L)
)
)
})
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment