如何用renderTable结合CSS/HTML实现带横向进度条的表格?
在Shiny中实现带横向百分比进度条的表格
方法一:使用DT包(推荐)
DT包的datatable支持自定义列渲染,能快速实现进度条效果,代码如下:
ui.R
library(shiny) library(DT) ui <- fluidPage( fluidRow( column(6, DTOutput("horizontalBarTable")) # 替换为DT专属输出组件 ) )
server.R
server <- function(input, output) { data <- data.frame( Category = c("Category A", "Category B", "Category C"), Percentage = c(30, 50, 70) ) output$horizontalBarTable <- renderDT({ datatable(data, rownames = FALSE) %>% formatStyle( "Percentage", background = styleColorBar(c(0, 100), "#4CAF50"), # 进度条颜色与取值范围 backgroundSize = "100% 80%", backgroundRepeat = "no-repeat", backgroundPosition = "center" ) }) }
该方案直接利用DT内置函数生成进度条,可通过调整styleColorBar的颜色参数、backgroundSize等属性修改进度条样式。
方法二:使用renderTable结合HTML/CSS
如果坚持使用renderTable,可以通过构造HTML进度条元素+自定义CSS实现效果:
ui.R
library(shiny) ui <- fluidPage( # 自定义进度条样式 tags$style(HTML(" .progress-container { width: 100%; background: #f0f0f0; border-radius: 4px; height: 20px; overflow: hidden; } .progress-fill { height: 100%; background: #4CAF50; color: white; font-size: 12px; line-height: 20px; text-align: center; } ")), fluidRow( column(6, tableOutput("horizontalBarTable")) ) )
server.R
server <- function(input, output) { data <- data.frame( Category = c("Category A", "Category B", "Category C"), Percentage = c(30, 50, 70) ) # 将百分比转为HTML进度条代码 data$Percentage <- sapply(data$Percentage, function(p) { sprintf( '<div class="progress-container"><div class="progress-fill" style="width: %d%%">%d%%</div></div>', p, p ) }) output$horizontalBarTable <- renderTable({ data }, sanitize.text.function = function(x) x, include.rownames = FALSE) }
这里通过sanitize.text.function = function(x) x确保HTML代码不被转义,能正常渲染出进度条样式。
内容的提问来源于stack exchange,提问作者user165426
相关产品推荐
相关产品推荐

