你如何在knitr pdf输出中调整绘图的大小

时间:2015-11-03 18:32:23

标签: r pdf ggplot2 knitr

我正在尝试使用knitr将一些ggplot输出发布到pdf文件。

我正在使用的命令是:

```{r, results = 'asis', echo=FALSE, warning=FALSE,tidy=FALSE}
    ggplot(data,aes(datetime, usedmem, group=machine, colour=machine))+geom_line()+
        geom_smooth(method="lm", se=T, colour="blue")+
        facet_wrap(~machine)+theme_bw()
```
  1. 是否可以设置整个绘图大小的大小。如果数据框中有许多服务器,则facet_wrap中的每个图都会缩小。

  2. 我每页看到一张图表,如何在花药后打印图表而不浪费任何空间?

2 个答案:

答案 0 :(得分:0)

To speak to your second question, try using the multiplot function found here. Like user2706569 said in the comment, this would require using knitr (just save your .rmw file as .Rnw) and adding in the following code. You can then call multiplot in whatever chunk you are using to generate the plots.

<<loadfunctions>>=

multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
  require(grid)
  plots <- c(list(...), plotlist)
  numPlots = length(plots)
  if (is.null(layout)) {
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)), ncol = cols, nrow = ceiling(numPlots/cols))
  }
 if (numPlots==1) {
    print(plots[[1]])
  } else {
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
    for (i in 1:numPlots) {
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row, layout.pos.col = matchidx$col))
    }
  }
}
@


<<myplots, results='asis', fig.width=8, fig.height=6>>==
multiplot(someplot_1, someplot_2, cols = 2)

@

答案 1 :(得分:0)

构建.Rnw文件,如下所示,将有所帮助。通过调整out.widthfig.heightfig.width,您可以控制“浪费的空间”问题。

\documentclass{article}
\begin{document}

Create several graphics
<<>>=
library(ggplot2)
plots <- lapply(unique(mpg$manufacturer),
                function(m) {
                  ggplot(mpg[mpg$manufacturer == m, ]) +
                  aes(x = model, y = cty) + 
                  geom_boxplot() +
                  ggtitle(m)
                })
@

<<echo = FALSE, results = "hide", out.width = "0.5\\textwidth">>=
plots
@

\end{document}