How to add elements to a plot using a knitr chunk

2019-02-16 20:25发布

问题:

For documentary purposes, I want some code for a plot in the html-output, but not the plot. Later, I have to call the plotting code, and add something to the plot, but only seeing the additional code. I tried this:

```{r non.finished.plotting, eval=FALSE}
    plot(1,type="n")
```
Some explanatory text here in the output:
"This produces an empty plot, and we could now add some points to it manually."

```{r add.layer, fig.width=5, fig.height=5}
<<non.finished.plotting, echo=FALSE>>
points(x=rnorm(100,1,0.1), y=rnorm(100,0.8,0.1) )

```

I have found the echo-notation at Yihui's, but when I knit this, I get an error message in the output.

## Error: plot.new has not been called yet

I also tried fiddling with the chunk options, but I could not find a combination which does what I want. (Sorry, this is very basic, but I did not find something quite like this example.)

回答1:

Chunk references in <<>> do not respect chunk options, so <<non.finished.plotting, echo=FALSE>> will not work. What you can do is to move the chunk option echo back to the main chunk like this:

```{r add.layer, fig.width=5, fig.height=5, echo=-1}
<<non.finished.plotting>>
points(x=rnorm(100,1,0.1), y=rnorm(100,0.8,0.1) )
```

echo=-1 means do not echo the first expression (as documented). This is probably what you want: