You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Shiny中为formattable表格手动设置条件格式边界

Manual Fixed Boundaries for Formattable in Shiny

Got it! You want to swap out the auto-calculated color range in your formattable for manual, fixed boundaries—totally doable. Here's how to tweak your Shiny app code to make that happen:

Modified Full Code

library(shiny)
library(formattable) # Explicitly load the formattable package

list1 <- c(0.2, 0.8, 0.5)
list2 <- c("element1", "element2", "element3")
df <- data.frame(list1, list2)

UI <- fluidPage(
  formattableOutput("table1")
)

Server <- function(input, output) {
  output$table1 <- renderFormattable({
    formattable(df, list(
      list1 = formatter("span",
                        style = function(x) {
                          # Set your manual boundaries here
                          min_bound <- 0  # Value that maps to full green
                          max_bound <- 1  # Value that maps to full red
                          
                          # Normalize values, clamping any outliers to 0-1 range
                          normalized <- pmax(pmin((x - min_bound)/(max_bound - min_bound), 1), 0)
                          
                          # Generate gradient from green (0,1,0) to red (1,0,0)
                          bg_color <- rgb(normalized, 1 - normalized, 0)
                          
                          style(background = bg_color)
                        })
    ))
  })
}

shinyApp(ui = UI, server = Server)

Key Changes Explained

  • Replaced auto-scaled color_tile: Instead of relying on color_tile to use the column's min/max values, we built a custom formatter function to take full control of the color range.
  • Manual boundary control: Adjust min_bound and max_bound to any values you need. For example, if you want 0.3 to be the green threshold and 0.7 to be the red threshold, just update those two variables.
  • Outlier clamping: The pmax(pmin(...)) line ensures any values outside your set boundaries don't break the color gradient—values below min_bound will show full green, and values above max_bound will show full red.
  • Explicit package load: Added library(formattable) to avoid runtime errors if the package isn't already loaded in your environment.

内容的提问来源于stack exchange,提问作者Henk Straten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:32:11