如何在knitr中设置绘图的宽度/高度?

时间:2015-02-08 10:11:07

标签: r plot knitr

我有一些R代码,我打开一个png()设备来编写一个绘图,但我希望这个绘图也显示在我使用Knit-R从代码生成的PDF中。

到目前为止,我已经这样做了:

png(file="filename.png", width=5, height=5, units="in", res=300)
dev.control(displaylist="enable")
# Do the plotting here
dev.off()

这将创建带有情节的filename.png,并且还会显示Knit-R生成的PDF中的情节,因为dev.control()调用。但是,生成的PDF中的绘图大小有点偏。我希望大小保持我给png()函数的宽高比。我该怎么做?

注意:这是一个R文件,而不是一个Rnw文件。没有任何LaTeX,只有R代码,我使用"文件>针织"来自R-Studio的命令(Ctrl-Shift-K)。

1 个答案:

答案 0 :(得分:3)

RStudio在此运行knitr's spin function,因此您可以将块选项写入正在运行的代码上方的R注释中。例如:

#-name, fig.width=5, fig.height=5
png(file="filename.png", width=5, height=5, units="in", res=300)
dev.control(displaylist="enable")
plot(rnorm(10))
dev.off()

这将生成5x5图像:

enter image description here