将ggplot嵌入到knitr文档中失败 [英] Embedding ggplot into knitr document fails
问题描述
我正在使用R-Studio/Knit创建文档,并希望通过在文档部分(例如,
I'm creating a document using R-Studio / Knit and want to organize my work by creating graphics and tables etc before using them in the a document part, e.g.
mygraph1 <- ggplot(<whatever is needed>)
```
In this document I want the graphs shown after this line
`r mygraph1`
and before this
```{r, echo=FALSE}
但是我得到的是一条错误消息
but what I get is an error message
vapply(x,format_sci_one,character(1L),...,USE.NAMES = FALSE)中的错误:值的长度必须为1,但FUN(X [[1]])结果为3次调用:...粘贴-> hook .inline.hook-> format_sci-> vapply unlockBinding("params",)中的错误:"params"没有绑定调用:-> do.call-> unlockBinding执行暂停
Error in vapply(x, format_sci_one, character(1L),..., USE.NAMES=FALSE) : Values must be length 1, but FUN(X[[1]]) result is 3 Calls: ... paste -> hook .inline.hook -> format_sci -> vapply Error in unlockBinding("params",) : no binding for "params" Calls : -> do.call -> unlockBinding Execution halted
(我希望我能够正确复制错误消息,似乎尚未从R Markdown窗口中找到复制/粘贴的地方)
(I hope I was able to copy the error message right, seems not yet found copy/paste from R Markdown window)
解决此问题的一种方法是将图形输出到png文件中,而不是在脚本的前一部分中,然后链接到png.但是还有其他/更优雅的方法吗?
A way to resolve this is to output the graphs into png files instead in a previous part of the script and then link to the pngs.. But is there any other / more elegant way to do this?
下面更新了一个真实的示例,但是使用了plot,因为它会产生相同的效果(并且让我更快地展示出来)
Updated with a real sample below but using plot instead as it produces the same effect (and is quicker for me to demonstrate)
```{r setup, include=FALSE}
library(knitr)
n <- 5
df <- data.frame(x=seq(1,n),y=rnorm(n))
df_kable <- kable(df)
df_plot <- plot(df)
```
## My chapter
Tabular data works fine like this embedded in text
`r df_kable`
and it would be so cool if plot etc would work the same way as well..
`r ds_plot`
But looks it does not. So sad..
```{r echo=FALSE}
推荐答案
图形应以块而不是内联代码的形式呈现.这是一个示例.Rmd文件和生成的.html输出.
Graphics should be rendered in chunks, not in-line code. Here is an example .Rmd file and the resulting .html output.
---
title: Embedding ggplot into knitr document fails
---
We will generate a graphic in the following chunk.
```{r}
library(ggplot2)
mtcars_ggplot <-
ggplot(mtcars) +
aes(x = wt, y = mpg) +
geom_point() +
stat_smooth()
```
In-line code is great for things like summary statistics. The mean miles per gallon for the `mtcars` data set is `r mean(mtcars$mpg)`.
In-line code is not good for graphics, as you know.
Instead, use a chunk. This will also allow you to control how the graphic is
rendered in your final document.
```{r show_figure, fig.width = 3, fig.height = 3}
mtcars_ggplot
```
这篇关于将ggplot嵌入到knitr文档中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!