R中将常规表格转为带边框ggplot表格,解决knit输出PDF数字变井号问题
问题原因
base R原生表格输出在knit为PDF时,默认分配的列宽不足以容纳长数字,会直接截断显示为#,同时原生表格无默认边框样式,可读性差。
解决方案:基于ggplot构建带边框表格
方法1:纯ggplot2原生实现(无需额外安装扩展包)
完整可运行代码如下:
# 加载ggplot2 library(ggplot2) # 你的原有表格生成代码 reftable <- matrix(c("181198", "234321", "306789", "16000234"), ncol = 1, byrow = TRUE) colnames(reftable) <- c("Score") rownames(reftable) <- c("How I Met Your Mother", "There Are No Ifs, Ands, Or Buts in the Land of Fantasies and Dreams", "Leo and Carrie Simply Cannot Get Along", "Parry Needs A Dentist") reftable <- as.table(reftable) # 转换为数据框适配ggplot df <- as.data.frame(reftable, stringsAsFactors = FALSE) colnames(df) <- c("作品名称", "分数") df$行号 <- nrow(df):1 # 调整行顺序和表头匹配 # 构建表格 ggplot() + # 绘制表头单元格 geom_tile(aes(x = c(1,2), y = nrow(df)+1), color = "black", fill = "white", size = 0.8, width = c(6,1)) + annotate("text", x = 1, y = nrow(df)+1, label = "作品名称", fontface = "bold", size = 3.5) + annotate("text", x = 2, y = nrow(df)+1, label = "分数", fontface = "bold", size = 3.5) + # 绘制内容单元格 geom_tile(data = df, aes(x = 1, y = 行号), color = "black", fill = "white", size = 0.8, width = 6) + geom_tile(data = df, aes(x = 2, y = 行号), color = "black", fill = "white", size = 0.8, width = 1) + geom_text(data = df, aes(x = 1, y = 行号, label = 作品名称), size = 3, hjust = 0.5) + geom_text(data = df, aes(x = 2, y = 行号, label = 分数), size = 3.5) + # 去除多余样式 theme_void() + # 调整画布适配长文本 theme(plot.margin = unit(c(0.3,0.3,0.3,0.3), "cm")) + coord_equal(expand = FALSE)
knit时可调整代码块参数{r fig.width=10, fig.height=4}适配长作品名称的显示,不会出现数字截断问题。
方法2:使用ggpubr简化实现
需要先安装加载ggpubr包,代码更简洁:
library(ggpubr) # 沿用上面生成的df数据框 ggtexttable(df, rows = NULL, theme = ttheme( core = list(fg_params = list(hjust = 0.5, x = 0.5), bg_params = list(color = "black", fill = "white")), colhead = list(fg_params = list(fontface = "bold"), bg_params = list(color = "black", fill = "white")) ))
内容的提问来源于stack exchange,提问作者Macromind101
相关产品推荐
相关产品推荐

