在 Quarto 中为 kableExtra 表格的单独行着色
数据小陈
结论
在 Quarto 的 HTML 输出里,给数据行设置 background,优先用 kableExtra::row_spec()。row_spec() 的行号按表格行计算:表头是 0,第一条数据行是 1。按你的数据顺序,把 EPA AQI 颜色依次映射到第 1 到第 6 行即可。
可运行示例
library(kableExtra)
table_data <- data.frame(
visibility = c('>10', '6-9', '3-5', '1.5-2.5', '0.75-1.5', '<0.75'),
aqi = c('Good', 'Moderate', 'Unhealthy for Sensitive Groups',
'Unhealthy', 'Very Unhealthy', 'Hazardous'),
message = c(
'None.',
'Unusually sensitive people should consider reducing prolonged or heavy exertion.',
'People with respiratory or heart disease, the elderly, and children should limit prolonged exertion.',
'People with respiratory or heart disease, the elderly, and children should avoid prolonged exertion, everyone else should limit prolonged exertion.',
'People with respiratory or heart disease, the elderly, and children should avoid any outdoor activity, everyone else should avoid prolonged exertion.',
'Everyone should avoid any outdoor exertion, people with respiratory or heart disease, the elderly and children should remain indoors.'
)
)
aqi_colors <- c(
'Good' = '#00E400',
'Moderate' = '#FFFF00',
'Unhealthy for Sensitive Groups' = '#FF7E00',
'Unhealthy' = '#FF0000',
'Very Unhealthy' = '#8F3F97',
'Hazardous' = '#7E0023'
)
tbl <- kbl(
table_data,
format = 'html',
caption = 'EPA Air Quality Index categories'
) %>%
kable_styling(full_width = FALSE, bootstrap_options = 'condensed') %>%
row_spec(0, bold = TRUE)
for (i in seq_len(nrow(table_data))) {
tbl <- tbl %>%
row_spec(i, background = aqi_colors[[table_data$aqi[i]]])
}
tbl
如果你的 aqi 列顺序与颜色向量顺序完全一致,也可以显式写六次 row_spec():
kbl(table_data, format = 'html') %>%
kable_styling(full_width = FALSE, bootstrap_options = 'condensed') %>%
row_spec(0, bold = TRUE) %>%
row_spec(1, background = '#00E400') %>%
row_spec(2, background = '#FFFF00') %>%
row_spec(3, background = '#FF7E00') %>%
row_spec(4, background = '#FF0000') %>%
row_spec(5, background = '#8F3F97') %>%
row_spec(6, background = '#7E0023')
注意事项
row_spec()的background在 HTML 输出中最直接;Quarto 文档请确保该代码块输出到 HTML。PDF/LaTeX 下也可用,但受 LaTeX 颜色包和表格环境限制;Word/docx 下kableExtra的行背景支持较弱,通常需要改用其他表格方案。- 不要同时开启
striped等斑马纹样式,否则可能和自定义行背景叠加或覆盖。示例只保留condensed。 - 颜色值建议用 EPA AQI 常用十六进制色,而不是只写
green、yellow这类 CSS 颜色名,以避免实际显示色差。 - 黄色背景上如果文字对比度不够,可再对对应行用
color参数或 CSS 调整文字颜色。
备注:内容仅供参考。
