如何调整Quarto PDF文档的列宽及表格字体大小?
解决Quarto PDF中图表与表格并排的尺寸调整问题
核心解决方案
针对图表过小、表格字体调整编译错误的问题,可通过以下两步解决:
1. 自定义列宽比例放大图表
放弃默认的layout-ncol: 2(等分宽度),改用自定义列宽比例分配图表和表格的空间。在代码块开头添加#| layout: [[1.5, 1]],表示图表所在列宽度是表格列的1.5倍,你可以根据需求调整比例数值(比如[[2,1]]让图表占更大空间)。
同时为图表设置合适尺寸,添加#| fig.width: 6和#| fig.height: 4(数值可按需调整),确保图表在放大的列中显示清晰。
2. 修复表格字体调整的编译错误并占满列宽
之前使用kable_styling(full_width = F, font_size = 10)报错,是因为full_width=F与Quarto自动生成的LaTeX minipage布局冲突。改为以下两种方式之一:
方式一:调整kableExtra参数
使用full_width=TRUE让表格占满右侧列,同时设置字体大小:
kable(table[, c(1, 2)], row.names = FALSE, col.names = c("This is the species of the Iris", "Petal Width")) %>% kable_styling(full_width = TRUE, font_size = 10)
方式二:用LaTeX命令直接控制字体(更稳妥)
如果方式一仍报错,直接用LaTeX字体命令包裹表格,无需依赖kableExtra的font_size参数:
cat("\\begingroup\\small\n") kable(table[, c(1, 2)], row.names = FALSE, col.names = c("This is the species of the Iris", "Petal Width")) %>% kable_styling(full_width = TRUE) cat("\\endgroup\n")
\small会将表格字体缩小一级,你也可以用\footnotesize进一步缩小。
完整可复现代码
knitr::opts_chunk$set(echo = FALSE, comment = NA, tidy.opts=list(width.cutoff=60),tidy=TRUE, warning = FALSE)
library(tidyverse) library(tinytex) library(kableExtra)
table <- iris %>% group_by(Species) %>% summarize (PetalWidth = mean(Petal.Width), SepalLength = mean(Sepal.Length), SepalWidth = mean(Sepal.Width)) iris$Petal.Width <- as.factor(iris$Petal.Width) iris$Sepal.Length <- as.factor(iris$Sepal.Length) iris$Sepal.Width <- as.factor(iris$Sepal.Width)
#| layout: [[1.5, 1]] #| fig.width: 6 #| fig.height: 4 ggplot(iris, aes(x = Petal.Width, fill = Petal.Width)) + geom_bar(position = 'dodge', stat = 'count') # 方式一:kableExtra调整字体 kable(table[, c(1, 2)], row.names = FALSE, col.names = c("This is the species of the Iris", "Petal Width")) %>% kable_styling(full_width = TRUE, font_size = 10) # # 方式二:LaTeX命令控制字体(若方式一报错则用这个) # cat("\\begingroup\\small\n") # kable(table[, c(1, 2)], row.names = FALSE, col.names = c("This is the species of the Iris", "Petal Width")) %>% # kable_styling(full_width = TRUE) # cat("\\endgroup\n")
关键说明
layout: [[a, b]]中的a和b是相对宽度比例,数值越大,对应列的宽度占比越高。- 之前
fig.dim无效是因为layout-ncol会覆盖单独的尺寸设置,改用自定义layout后,配合fig.width和fig.height即可生效。 - 表格设置
full_width=TRUE后会自动填满右侧列的空间,缩小字体后能避免内容溢出。
内容的提问来源于stack exchange,提问作者EmpiricalOstrich
相关产品推荐
相关产品推荐

