Plot显示在renderTable中,但不显示在DT :: renderDataTable中

时间:2018-02-08 02:54:10

标签: r plot shiny dt

我试图将一个小的情节放入一个闪亮的DT::dataTableOutput中,而我可以将一个情节放入一个tableOutput而没有任何问题,它在DT版本中根本不会显示。

library(shiny)
ui <- fluidPage(
  DT::dataTableOutput("data1"),
  tableOutput("data2")
)

server <- function(input, output) {
  output$data1 <- DT::renderDataTable({
    dat <- cars[1:5,]
    dat$test <- c("a","b","c","d",
      '<div id="testPlot1" class="shiny-plot-output" style="width: 100px ; height: 100px"></div>')
    dat
  },escape=FALSE)
  output$data2 <- renderTable({
    dat <- cars[1:5,]
    dat$test <- c("a","b","c","d",
      '<div id="testPlot2" class="shiny-plot-output" style="width: 100px ; height: 100px"></div>')
    dat
  }, sanitize.text.function = function(x) x)
  output$testPlot1 <- renderPlot({
    par(mar=c(0,0,0,0))
    plot(cars[[1]],cars[[2]])
  },height=100,width=100)
  output$testPlot2 <- renderPlot({
    par(mar=c(0,0,0,0))
    plot(cars[[1]],cars[[2]])
  },height=100,width=100)
  outputOptions(output, 'testPlot1', suspendWhenHidden=FALSE)
}

shinyApp(ui, server)

plot expected in red circle

1 个答案:

答案 0 :(得分:0)

我认为问题在于表格稍后呈现。

一种可能性是使用plotOutput渲染图,然后使用JavaScript将其移动到单元格中:

js <- c(
  "function(){",
  "  var $plot = $('#testPlot1');",
  "  var $td = $('#data1').find('table').find('tr:last-child').find('td:last-child');",
  "  $td.append($plot);",
  "}"
)

ui <- fluidPage(
  plotOutput("testPlot1", width = "100px", height = "100px"),
  DT::dataTableOutput("data1"),
  tableOutput("data2")
)

server <- function(input, output) {
  output$data1 <- DT::renderDataTable({
    dat <- cars[1:5,]
    dat$test <- c("a","b","c","d","")
    dat
  }, escape=FALSE, options = list(initComplete = JS(js)))
  output$testPlot1 <- renderPlot({
    par(mar=c(0,0,0,0))
    plot(cars[[1]],cars[[2]])
  },height=100,width=100)
}

shinyApp(ui, server)

enter image description here

在这里,我已经选择了目标单元格,因为它是最后一行的最后一个单元格。更为通用的策略是将divid放在目标单元格中​​,如下所示:

  output$data1 <- DT::renderDataTable({
    dat <- cars[1:5,]
    dat$test <- c("a","b","c","d",'<div id="target"></div>')
    dat
  }, escape=FALSE, options = list(initComplete = JS(js)))

,然后您可以像这样选择它:

js <- c(
  "function(){",
  "  var $plot = $('#testPlot1');",
  "  var $td = $('#data1 #target');",
  "  $td.append($plot);",
  "}"
)