0

With the following Shiny App I would like to update the plot according to the ordering in the data table, i.e. if I sort the data by x in the data table, it should automatically apply that sorting to the plot. How would I go about it? Does data table have an input variable like rows_selected for the current sorting?

test-data

testdata <- data.frame(x = round(runif(10)*100), y = round(runif(10)*100))
rownames(testdata) <- LETTERS[1:10]

ui.R

require(DT)

ui <- fluidPage(
  
  fluidRow(
    plotOutput("plot")
  ),
  fluidRow(
    DT::dataTableOutput("table")
  )
  
)

server.R

server <- function(input, output) {
  

  output$plot <- renderPlot({
    
    barplot(testdata[,1])
    
  })
  
  output$table <- DT::renderDataTable({
    
    DT::datatable(
      testdata
    )
    
  })
  
}

shinyApp(ui, server)
sedsiv
  • 531
  • 1
  • 3
  • 15

1 Answers1

0

In the example below, the plot is re-ordered based on the column selected in the table below.

library(shiny)
library(DT)

ui <- fluidPage(
  plotOutput("plot"),
  DTOutput("table") #, DTOutput("table2") 
)

server <- function(input, output) {
  rv <- reactiveValues(data=NULL,
                       data2=NULL)
  
  output$table <- renderDT({
    
    rv$data <- data.frame(
      Name = c("Person A", "Person B", "Person C", "Person D"), 
      Metric_1 = c(8, 7, 4, 10), 
      Metric_2 = c(3, 5, 2, 8)
    )
    rv$data2 <- rv$data
    
    datatable(rv$data, extensions = 'Select', 
                       options = list(select = list(style = 'single', items = 'column'),
                                      ordering = TRUE, searching = FALSE, pageLength = 10), 
              selection = 'none')
    
  }, server = FALSE)
  
  observeEvent(input$table_columns_selected,{
    df <- rv$data[order(rv$data[,input$table_columns_selected]), ]
    output$table2 <- renderDT({
      subset_table <- df[, input$table_columns_selected, drop = F]
      datatable(subset_table)
    })
  
    rv$data2 <- df
    
  })
  
  output$plot <- renderPlot({
    barplot(rv$data2[,2])
  })
}

shinyApp(ui = ui, server = server)
YBS
  • 19,324
  • 2
  • 9
  • 27
  • Not quite. In the data table I can click beside the column names to sort the table and that's what I would like to pass to the plot. – sedsiv Feb 24 '21 at 17:08
  • @sedsiv, please try the updated code. I am not sure if this will meet your needs. – YBS Feb 25 '21 at 14:11
  • sorry for the late reply. your solution doesn't sort it by user interaction. – sedsiv Mar 22 '21 at 18:45