[英]R shiny renderTable change cell colors
我有一个表格,想根据 X(=6) 不同深浅蓝色中的值 (0-100) 为每个单元格着色。 该表显示在 TabPanel 中。
目前我正在使用 Shinyjs 调用一个 javascript 函数,该函数选择我的表格并将 CSS 样式添加到<td>
标签,具体取决于值范围。
问题是,在第一次加载表格时(点击 TabPanel),没有颜色显示,只有在重新加载之后。
所以我要么在 R 中寻找解决方案(不需要额外的 Javascript),要么寻找一种自动重新加载 Table/TabPanel 的方法。
library(shiny)
ui <- shinyUI(fluidPage(
tableOutput("dataTable")
))
server <- shinyServer(function(input, output) {
output$dataTable <- renderTable({
data <- getDataFromSomeWhere();
//Some operations on data
data
//I want to color every table cell, depening on value (f.e. 0-5 = white, 10-20 = light blue ...)
}, rownames = TRUE, colnames = TRUE)
shinyApp(ui = ui, server = server)
UPDATE最后,我仍然使用 JavaScript 解决方案,但使用闪亮的特定 js 事件来获得所需的效果:
$(document).on("shiny:value", function(e) {
if (e.name == "myComponent") {
e.preventDefault();
$('#myComponent').html(e.value);
//color code etc.
}
您可以使用tableHTML
创建一个表格并有条件地设置它的样式。
library(shiny)
library(tableHTML)
更改ui
以使用tableHTML
的输出函数:
ui <- shinyUI(fluidPage(
tableHTML_output("dataTable")
))
然后使用render_tableHTML()
来呈现在其中生成的表格。
您可以使用函数tableHTML()
创建一个纯 HTML 表格。 然后您可以使用add_css_conditional_column()
创建条件(在这种情况下between
)来更改背景颜色(注意:您也可以使用其他 css。我在示例中使用了#f6f6f6
而不是white
,因为您不会看到输出差异)
server <- shinyServer(function(input, output) {
getDataFromSomeWhere <- reactive({
mtcars
})
output$dataTable <- render_tableHTML({
data <- getDataFromSomeWhere();
# //Some operations on data
data %>%
tableHTML(rownames = TRUE) %>%
add_css_conditional_column(conditional = 'between',
between = c(0, 5),
css = list(c('background-color'),
c('#f6f6f6')),
columns = 1:ncol(data)) %>%
add_css_conditional_column(conditional = 'between',
between = c(10, 20),
css = list(c('background-color'),
c('lightblue')),
columns = 1:ncol(data))
})
})
最终结果是:
shinyApp(ui = ui, server = server)
您可以在小插图中找到有关如何使用tableHTML
更多详细信息。
我认为最好的解决方案是使用DT
库功能。 桌子更美观,还保留了可滚动的桌子功能。 两者都立即缺乏tableHTML
。
服务器包含renderDataTable
函数,用户可以在其中有条件地格式化表:
server <- shinyServer(function(input, output) {
output$beautifulTable <- DT::renderDataTable({
# display top 5 rows at a time
options(DT.options = list(pageLength = 5))
# example dataframe
df = as.data.frame(cbind(matrix(round(rnorm(50), 3), 10), sample(0:1, 10, TRUE)))
# set conditions and return the beautiful table
return(datatable(df) %>% formatStyle('V6', backgroundColor = styleEqual(c(0, 1), c('gray', 'yellow'))))
})
}
UI 简单地调用dataTableOutput
:
ui <- shinyUI(fluidPage(
# display the beautiful table
dataTableOutput("beautifulTable")
))
显示结果:
shinyApp(ui = ui, server = server)
你会得到: 更多例子在这里: https : //rstudio.github.io/DT/010-style.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.