如何使用ggplot2控制绘图的尺寸/大小

时间:2010-07-29 22:14:09

标签: r ggplot2

我正在使用ggplot2(分别是qplot)来生成一个包含Sweave的报告。现在我需要一些帮助来调整绘图的大小。我使用以下Sweave代码来包含它。

\begin{figure}[htbp]
\begin{center}
<<fig=true,echo=false>>=
print(mygraph)
@
\caption{MyCaption}
\end{center}
\end{figure}

如果我添加一个宽度参数(如下图所示),将图表压缩,但不会真正按比例缩小。

<<fig=true,echo=false,width=3>>=

如果我改用ggsave(),我可以使用scale参数并影响生成的.pdf文件的大小。有没有办法影响绘图的尺寸而不保存它(因为.pdf是由Sweave生成的)?我需要添加到qplot代码中吗?

mygraph=qplot(date,value,data=graph1,geom="line",colour=variable,xlab="",ylab="")
+ scale_y_continuous(limits = c(-0.3,0.3))

提前获得任何建议!

2 个答案:

答案 0 :(得分:5)

而不是在ggplot2中执行此操作,而是在打印图形的代码块之前添加以下LaTeX代码。

\SweaveOpts{width=x, height=y}

xy是以英寸为单位的高度和宽度。

如果您希望自己的情节具有特定的宽高比,则可以使用ggplot2opts()中进行设置。除非我有其他原因,否则根据Tufte的建议,我通常会尝试将我的情节缩小到黄金比例。通常我有

...
SweaveOpts{width=8, height=5}
...
<<label = "makeplot", echo = F>>=
  p <- ggplot(mpg, aes(displ, hwy)) + 
    geom_point()+
    opts(aspect.ratio = 2/(1+sqrt(5)) )
@
...
\begin{figure}[htbp]
\begin{center}
<<fig=true,echo=false>>=
  print(p)
@
\caption{MyCaption}
\end{center}
\end{figure}

答案 1 :(得分:2)

Sweave选项widthheight会影响PDF文件的尺寸,但不会影响文档中图形的大小。加上像

这样的东西
\setkeys{Gin}{width=0.4\textwidth}
\begin{document}之后

获得较小的图。

来源:Sweave manual,秒。 4.1.2