在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 oncolor_tileto 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_boundandmax_boundto 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 belowmin_boundwill show full green, and values abovemax_boundwill 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
相关产品推荐
相关产品推荐

