问题
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