R/topic2html.R

Defines functions topic2html

Documented in topic2html

#' Build crosstalk widget for visualizing topic model.
#'
#' @name topic2html
#' @param x a list of data frames -- from dtm2topic
#' @param top_n an integer
#' @param title a string
#' @return A crosstalk widget
#'
#' @export
#' @rdname topic2html
#'
#'
topic2html <- function(x,
                       top_n = 20,
                       title = NULL){

  pts <- data.table::setorder(x$beta, -beta)[, head(.SD, top_n), keyby = topic]
  pts$beta <- round(pts$beta, 4)
  sd_points <- crosstalk::SharedData$new(x$tsne,
                                         group = "tm",
                                         key = ~topic)
  sd_features <- crosstalk::SharedData$new(pts,
                                           group = "tm",
                                           key = ~topic)


  p <- plotly::plot_ly(data = sd_points,
                 x = ~X1,
                 y = ~X2,
                 marker = list(size = 25,
                               color = '#a5c8e1'))|>
    #plotly::add_markers() |>
    plotly::add_text(text = ~topic,
                     textposition="center",
                     showlegend = F)

  p1 <- p |>
    plotly::layout(showlegend = F,
                   autosize = T,
                   title = paste0('Intertopic Distance Map via tSNE:\n ', title)) |>
    plotly::style(hoverinfo = 'none') |>
    plotly::highlight(on = 'plotly_hover',
                      opacityDim = .75)

  t1 <- sd_features |>
    DT::datatable(rownames = FALSE,
                  width = "100%",
                  options = list(#dom = 't',
                    options = list(scrollY = TRUE),
                    pageLength = 10)) |>

    DT::formatStyle(names(pts[,3]),
                    background = DT::styleColorBar(range(pts[,3]),
                                                   '#cc474d'),
                    backgroundSize = '80% 70%',
                    backgroundRepeat = 'no-repeat',
                    backgroundPosition = 'right') |>

    DT::formatStyle(columns = c(1, 2, 3), fontSize = '90%')

  crosstalk::bscols (list(p1, t1))

}
jaytimm/text2df documentation built on July 21, 2023, 1:58 a.m.