How to set the width/height of a plot in knitr?

被刻印的时光 ゝ 提交于 2019-12-08 07:33:49

问题


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()

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?

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).


回答1:


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()

This will produce a 5x5 image:



来源:https://stackoverflow.com/questions/28392767/how-to-set-the-width-height-of-a-plot-in-knitr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!