如何在knitr中设置绘图的宽度/高度? [英] How to set the width/height of a plot in knitr?
问题描述
我有一些R代码,我在其中打开png()设备来写图,但是我希望该图也显示在使用Knit-R从代码生成的PDF中.
I have some R code, where I open a png() device to write a plot to, but I want this plot to also show in the PDF that I generate from the code using Knit-R.
到目前为止,我已经做到了:
So far, I have done this:
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()函数提供的宽高比.我该怎么办?
This creates the filename.png
with the plot in it, and it will also show me the plot in the Knit-R generated PDF, because of the dev.control()
call. However, the size of the plot in the generated PDF is a bit off. I would like the size to retain the width and height ratio that I gave to the png() function. How do I do that?
注意:这是一个R文件,而不是Rnw文件.根本没有LaTeX,只有R代码,我使用R-Studio的文件>编织"命令(Ctrl-Shift-K).
Note: this is an R file, not an Rnw file. There is no LaTeX whatsoever, just R code, and I use the "File > Knit" command from R-Studio (Ctrl-Shift-K).
推荐答案
RStudio正在运行 knitr的
RStudio is running knitr's spin
function on this, so you can write chunk options into an R comment above the code you're running. For example:
#-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的图像:
This will produce a 5x5 image:
这篇关于如何在knitr中设置绘图的宽度/高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!