如何在使用ttheme_minimal的tableGrob中设置列宽?
调整tableGrob列宽的方法
tableGrob本身没有内置的列宽参数,但可以通过直接修改生成的grob对象的widths属性来自定义列宽,具体实现如下:
方法1:设置固定宽度
创建表格对象后,用unit()指定每列的固定宽度(支持英寸、厘米等单位):
team_free_agents <- structure(list(Player = c("Adrian Amos", "Dean Lowry", "Marcedes Lewis", "Allen Lazard", "Robert Tonyan", "Jarran Reed", "Randall Cobb", "Rudy Ford", "Yosh Nijman", "Keisean Nixon", "Justin Hollins" ), Position = c("S", "IDL", "TE", "WR", "TE", "IDL", "WR", "S", "LT", "CB", "EDGE"), Age = c(30, 29, 39, 28, 29, 31, 33, 29, 27, 26, 27), `Snap %` = c("94.6%", "46.7%", "41.2%", "78.9%", "54%", "68.2%", "33.9%", "42.8%", "69.1%", "28%", "40.7%"), `Current APY` = c("$9,000,000", "$6,775,000", "$4,000,000", "$3,986,000", "$3,750,000", "$3,250,000", "$3,000,000", "$1,137,500", "$965,000", "$965,000", "$706,724" ), `Current Guarantees` = c("$12,000,000", "$6,000,000", "$2,100,000", "$0", "$1,000,000", "$1,865,000", "$0", "$0", "$0", "$0", "$306,896" ), `2022 PFF Grade` = c(54.2, 59.3, 65.6, 69, 57.7, 61.9, 70.1, 77.7, 63.1, 63.9, 54)), row.names = c(NA, -11L), class = c("tbl_df", "tbl", "data.frame")) tt1 <- gridExtra::ttheme_minimal(base_size = 25) fa_table <- gridExtra::tableGrob(team_free_agents, rows = NULL, theme = tt1) # 自定义列宽:按顺序指定每列的宽度(单位为英寸) fa_table$widths <- unit(c(3, 1, 0.8, 1, 1.5, 1.5, 1.2), "inches") cowplot::draw_grob( fa_table, width = 90 )
方法2:按比例分配宽度
如果希望列宽按比例适配绘图区域,使用npc单位(0到1,代表整个绘图区域的比例):
# 替换上述的widths设置行 fa_table$widths <- unit(c(0.25, 0.1, 0.08, 0.1, 0.15, 0.15, 0.17), "npc")
关键说明
- 列宽的数量必须与表格的列数完全一致(示例中为7列)
- 常用单位:
inches(英寸)、cm(厘米)、npc(归一化比例)、lines(文本行高)
内容的提问来源于stack exchange,提问作者Sam Hoppen
相关产品推荐
相关产品推荐

