Issue
I've been using DT in my shiny apps for a while. I'm wondering if there is any option (easy way) to change a table header direction when the text is long (like rotate all colnames by 45 degree or something), This is a problem when you have many columns in a table. Thanks, Here is a short example:
library(shiny)
library(DT)
ui <- fluidPage(
mainPanel(
tabsetPanel(
tabPanel("Table", br(),
dataTableOutput("myTable"))
), width = 9
)
)
server <- function(input, output) {
output$myTable <- renderDataTable({
test <- data.frame(1:20, letters[1:20], stringsAsFactors = FALSE)
colnames(test) <- c("This is a long name", "This column name is much more longer!")
datatable(test, rownames = FALSE, options = list(autoWidth = TRUE, searching = TRUE, lengthMenu = list(c(5, 10, 25, 50, -1), c('5', '10', '25', '50', 'All')), pageLength = 10)) # %>% formatStyle(names(test))
})
}
shinyApp(ui, server)
Solution
Here is a way to rotate the headers by 90 degrees.
library(DT)
library(shiny)
headerCallback <- c(
"function(thead, data, start, end, display){",
" var $ths = $(thead).find('th');",
" $ths.css({'vertical-align': 'bottom', 'white-space': 'nowrap'});",
" var betterCells = [];",
" $ths.each(function(){",
" var cell = $(this);",
" var newDiv = $('<div>', {height: 'auto', width: cell.height()});",
" var newInnerDiv = $('<div>', {text: cell.text()});",
" newDiv.css({margin: 'auto'});",
" newInnerDiv.css({",
" transform: 'rotate(180deg)',",
" 'writing-mode': 'tb-rl',",
" 'white-space': 'nowrap'",
" });",
" newDiv.append(newInnerDiv);",
" betterCells.push(newDiv);",
" });",
" $ths.each(function(i){",
" $(this).html(betterCells[i]);",
" });",
"}"
)
ui <- fluidPage(
DTOutput("table")
)
server <- function(input, output){
output[["table"]] <- renderDT({
datatable(iris,
options = list(
headerCallback = JS(headerCallback),
columnDefs = list(
list(targets = "_all", className = "dt-center")
)
))
})
}
shinyApp(ui, server)
Answered By - Stéphane Laurent
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.