当使用gridExtra包中的nice feature tableGrob()来绘制由Rmarkdown和knitr生成的html文档中的表时,我有以下问题。
这是一个可重复的例子:
library(datasets) library(dplyr) mtcars$cyl <- as.factor(mtcars$carb) carb.mpg <- mtcars %>% select(carb,mpg) %>% group_by(carb) %>% summarise_each(funs(sum(.,na.rm=TRUE)),-carb) %>% arrange(desc(mpg)) ##plot the table tab <- tableGrob(carb.mpg, cols=c("carb","mpg"), theme=ttheme_minimal()) grid.arrange(tab, top=textGrob("Cars MPG per CARB",gp=gpar(fontsize=16,font=1)) )对于knitr一般块选项:
title: "Test with cars" output: html_document: keep_md: true{r setoptions, echo=FALSE} library(knitr) opts_chunk$set(message=FALSE,warning=FALSE)
从附加快照中可以看出的问题是巨大的空间 表与其标题和图例之间。 如果我可以在文档中左对齐表格也会很好。
任何帮助将非常感激。
I have the following issues when using the nice feature tableGrob() from gridExtra package to plot a table in an html document produced by Rmarkdown and knitr.
Here is a reproducible example:
library(datasets) library(dplyr) mtcars$cyl <- as.factor(mtcars$carb) carb.mpg <- mtcars %>% select(carb,mpg) %>% group_by(carb) %>% summarise_each(funs(sum(.,na.rm=TRUE)),-carb) %>% arrange(desc(mpg)) ##plot the table tab <- tableGrob(carb.mpg, cols=c("carb","mpg"), theme=ttheme_minimal()) grid.arrange(tab, top=textGrob("Cars MPG per CARB",gp=gpar(fontsize=16,font=1)) )For knitr general chunk options:
title: "Test with cars" output: html_document: keep_md: true{r setoptions, echo=FALSE} library(knitr) opts_chunk$set(message=FALSE,warning=FALSE)
The issue as can been seen from the attached snapshot is the huge space between the table and its title and legend. It would be also nice if I could left-align the table in the document.
Any help would be much appreciated.
最满意答案
你可以试试这个
tg <- textGrob("Cars MPG per CARB", gp=gpar(fontsize=16,font=1)) grid.arrange(tg, tab, heights=unit.c(grobHeight(tg), sum(tab$heights)), vp=viewport(x=unit(0,"npc") + 0.5*unit.pmax(grobWidth(tg), sum(tab$widths))))
After some tweaking, I found that the position of the table can be controlled using viewport (x and y); width/height seem obsolete.
#plot the table tab <- tableGrob(carb.mpg, cols=c("carb","mpg"), theme=ttheme_minimal()) grid.newpage() vp <- viewport(width=0.90,height=0.90,x=0.10,y=0.80,clip="on") pushViewport(vp) grid.draw(tab)This solves the problem only partially: the huge vertical space is still there.
Perhaps this gives some direction to resolving the issue?
EDIT: one way that worked for me to control the white spaces/margins was to reduce the figure size parameters in knitr chunk options, i.e.,
{r plot mpg cars, fig.height=value, fig.width=value}
更多推荐
发布评论