首页 > 解决方案 > Shiny的DT中styleColorBar行的比较

问题描述

我想用 styleColorBar 做行比较。在这个示例中,我想逐行比较 Sepal.Length 和 Sepal.Width。

应用程序.R

library(shiny)
library(DT)

shinyApp(
  ui = fluidPage(DT::dataTableOutput("table")),
  server = function(input, output) {
    iris2 <- iris[c(1:10),c(1,2)]
    
    observe({
      
      output$table <- DT::renderDataTable({
        dat <- datatable(iris2,
                         options = list(
                           paging = FALSE
                         )) %>%
          formatStyle('Sepal.Length',background = styleColorBar(iris2$Sepal.Length, '#66cdaa'),backgroundSize = '98% 88%',backgroundRepeat = 'no-repeat', backgroundPosition = 'center') %>%
          formatStyle('Sepal.Width',background = styleColorBar(iris2$Sepal.Width, '#66cdaa'),backgroundSize = '98% 88%',backgroundRepeat = 'no-repeat', backgroundPosition = 'center')
        return(dat)
      })
      
    })
    
  })

但是由于styleColorBar是对每一列进行比较,所以左右最大值和最小值不一样,条形长度不匹配

应用程序.R

library(shiny)
library(DT)

shinyApp(
  ui = fluidPage(DT::dataTableOutput("table")),
  server = function(input, output) {
    iris2 <- iris[c(1:10),c(1,2)]
    
    observe({
      
      max <- max(iris2[,1:2], na.rm = TRUE)
      max <- c(max,max)
      min <- min(iris2[,1:2], na.rm = TRUE)
      min <- c(min,min)
      iris2 <- rbind(iris2,max,min)
      
      output$table <- DT::renderDataTable({
        dat <- datatable(iris2,
                         options = list(
                           paging = FALSE
                         )) %>%
          formatStyle('Sepal.Length',background = styleColorBar(iris2$Sepal.Length, '#66cdaa'),backgroundSize = '98% 88%',backgroundRepeat = 'no-repeat', backgroundPosition = 'center') %>%
          formatStyle('Sepal.Width',background = styleColorBar(iris2$Sepal.Width, '#66cdaa'),backgroundSize = '98% 88%',backgroundRepeat = 'no-repeat', backgroundPosition = 'center')
        return(dat)
      })
      
    })
    
  })

因此,我在每一列中添加了 Sepal.Length 和 Sepal.Width 的最大值和最小值的记录,并使条形长度相等。酒吧里的左右比较很顺利,但不是很酷。有没有办法向用户隐藏最后两行?或者我可以在不添加两条线的情况下证明左右条的合理性吗?

标签: rshinydt

解决方案


你可以做

library(DT)

iris2 <- iris[1:10, c(1,2)]
datatable(iris2,
          options = list(
            paging = FALSE
          )) %>%
  formatStyle('Sepal.Length', 
              background = styleColorBar(c(iris2$Sepal.Length, iris2$Sepal.Width), '#66cdaa'), 
              backgroundSize = '98% 88%', 
              backgroundRepeat = 'no-repeat', 
              backgroundPosition = 'center') %>%
  formatStyle('Sepal.Width', 
              background = styleColorBar(c(iris2$Sepal.Length, iris2$Sepal.Width), '#66cdaa'), 
              backgroundSize = '98% 88%', 
              backgroundRepeat = 'no-repeat', 
              backgroundPosition = 'center')

推荐阅读