I'm using R sweave (*.Rnw) and want to generate only plotname.eps.
\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
\SweaveOpts{eps=TRUE}
<<plotname, fig=TRUE, echo=F, prefix=F>>=
ggplot(data=data, aes(x = day, y = outside_act))
#
\end{document}
When I compile this code, three plots are generated: plotname.eps and plotname.pdf.
How can I suppress R sweave from generating plotname.pdf? (I only need plotname.eps and I don't want R sweave to run this chunk an additional times.)
You can use \SweaveOpts{eps=TRUE, pdf=FALSE}. For full details on the options available, run vignette("Sweave") in the R console.
However, if all you want is the EPS file and not the document, you can just generate it directly, using
setEPS()
postscript("filename.eps")
ggplot(data=data, aes(x = day, y = outside_act))
dev.off()
in an R script.
Related
\begin{figure}[h]
\centering
<<echo=FALSE>>=
for(i in 2:38){
print(my_plot_function(i))
}
#
\end{figure}
This is my code, but what is happening is that when I compile my PDF I only get the first two plots that fit on the first page and I do not get the rest of the plots.
I would like to have all of the plots on separate pages.
And how would I go about adding captions to each individual plot in the for loop.
\documentclass{article}
\begin{document}
<<echo = FALSE, fig.cap = c("First, Second, Third"), results = "asis">>=
library(ggplot2)
for (i in 1:3) {
print(qplot(x = 1, y = i))
cat("Arbitrary \\LaTeX code! \\clearpage")
}
#
\end{document}
You can use the chunk option fig.cap to add captions to your plots. Note that this will wrap your figure in a figure environment, turning it into a float.
Use the chunk option results="asis" to be able to print arbitrary text (including LaTeX markup) into your document using cat().
I have an issue with knitr and ggplot2 in Latex. I am trying to create a dynamic document with knitr. All my plots are in ggplot2. Hear me out:
I created the Latex document
I opened it in R Studio and saved the TEX file as RNW file. Global and Project options: knitr.
I pasted the R script there like:
<<echo=FALSE>>=
knitr::opts_chunk$set(fig.path='graphs/',
echo=FALSE, warning=FALSE, message=FALSE)
#
<<>>=
library(ggplot2)
library(tidyverse)
#
<<plot1>>=
my_data1 <- read.csv(file.choose(), header=TRUE, sep=",")
plot1 <- ggplot(data=my_data1, aes(x = pos , y = sum)) +
geom_line(colour = 'black', size = 1) +
scale_y_continuous(trans = 'log10', limits = c(1,100)) +
theme_classic() +
labs (x = 'axis_name1', y = 'axis_name2') +
coord_cartesian(xlim = c(1219890,1220102)) +
#
Everything is going well, except the graph does not show when I press 'Compile PDF' or in the graphs directory. However when I select only the R code and run it everything is fine(as long as I add print()). I managed to use TikZ which works just fine but without creating a dynamic document. I thought it was possible to output the plot directly in the PDF document but for some reason ggplot2 does not work. Is there something that I am missing?
Thank you.
I am trying to print a simple plot with knitr markdown.
below is my code.
```{Simple plot}
library(datasets)
with(airquality, plot(Wind, Ozone))
```
If I run this in r code file, it returns the plot properly.
However, when running this in a markdown file, it only shows code but no plot to the printed document.
what am I doing wrong?
Use ```{r} where r means R langage :
```{r}
library(datasets)
with(airquality, plot(Wind, Ozone))
```
I am using the knitr package for R to produce a LaTeX document combining text with embedded R plots and output.
It is common to write something like this:
We plot y vs x in a scatter plot and add the least squares line:
<<scatterplot>>=
plot(x, y)
fit <- lm(y~x)
abline(fit)
#
which works fine.
(For those not familiar with knitr or Sweave, this echos the code and output in a LaTeX verbatim environment and also adds the completed plot as a figure in the LaTeX document.)
But now I would like to write more detailed line-by-line commentary like:
First we plot y vs x with a scatterplot:
<<scatterplot>>=
plot(x, y)
#
Then we regress y on x and add the least squares line to the plot:
<<addline>>=
fit <- lm(y~x)
abline(fit)
#
The problem is that there are now two knitr code chunks for the same plot. The second code chunk addline fails because the plot frame created in the first code chunk scatterplot is not visible to the code in the second code chunk. The plotting window doesn't seem to be persistent from one code chunk to the next.
Is there any way that I can tell knit() to keep the plot window created by plot() active for the second code chunk?
If that is not possible, how else might I achieve LaTeX-style commentary on code lines that add to existing plots?
One Day Later
I can now see that essentially the same question has been asked before, see:
How to build a layered plot step by step using grid in knitr? from 2013 and
Splitting a plot call over multiple chunks from 2016.
Another question from 2013 is also very similar:
How to add elements to a plot using a knitr chunk without original markdown output?
You can set knitr::opts_knit$set(global.device = TRUE), which means all code chunks share the same global graphical device. A full example:
\documentclass{article}
\begin{document}
<<setup, include=FALSE>>=
knitr::opts_knit$set(global.device = TRUE)
#
First we plot y vs x with a scatterplot:
<<scatterplot>>=
x = rnorm(10); y = rnorm(10)
plot(x, y)
#
Then we regression y and x and add the least square line to the plot:
<<addline>>=
fit <- lm(y~x)
abline(fit)
#
\end{document}
You can show code without evaluating it by adding the chunk option eval=FALSE. If you only want to show the final version of the plot with the regression line added, then use eval=FALSE for the first plot(x,y).
Then we add two chunks for the regression line: One is the complete code needed to render the plot, but we don't want to display this code, because we don't want to repeat the plot(x,y) call. So we add a second chunk that we echo, to display the code, but don't evaluate.
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r data}
set.seed(10)
x=rnorm(10)
y=rnorm(10)
```
First we plot y vs x with a scatterplot:
```{r scatterplot, eval=FALSE}
plot(x, y)
```
Then we regress y on x and add the least squares line to the plot:
```{r addline, eval=FALSE}
fit <- lm(y~x)
abline(fit)
```
```{r echo=FALSE}
plot(x,y)
fit <- lm(y~x)
abline(fit)
```
Here's what the output document looks like:
I would like to find a way to use the LaTeX \ref{} markup to comment in the R code within a Sweave .Rnw file. Here are two examples, one in print
http://cm.bell-labs.com/cm/ms/departments/sia/project/nlme/UGuide.pdf
and one to use to work with:
The .Rnw file
% File: example.Rnw
\documentclass{article}
\usepackage{fullpage}
\usepackage{graphics}
\usepackage{Sweave}
\usepackage[margin = 10pt, font=small, labelfont={bf}]{caption}
\begin{document}
Here is an example file to show what I want to do. I would like to figure out how to use the \LaTeX\ reference command to reference a figure being generated by R code. Note in the R code, in a comment there is a reference to the figure, but of course the output file shows a verbatim copy of the \LaTeX\ markup. Does anyone know how to get something for Figure \ref{fig2}?
<< example plot >>=
library(reshape)
library(ggplot2)
n <- 100
lambda <- 1 / 3
x <- seq(0, qexp(0.999, rate = lambda), length = n)
q1.a <- data.frame(x = x,
f = dexp(x, rate = lambda),
F = pexp(x, rate = lambda))
q1.a <- melt(q1.a, id.vars = 'x')
g <- ggplot(q1.a) + # Produces \ref{fig1}
aes(x = x, y = value) +
geom_line() +
facet_wrap( ~ variable, scale = "free_y")
ggsave(g, filename = "example1.jpeg")
#
\begin{figure}[h]
\centering
\includegraphics[width = 0.48\textwidth]{./example1}
\caption{Exponential Distribution based plots.}
\label{fig1}
\end{figure}
Here is more of what I would like to see:
<< example plot 2 >>=
ggsave(g + geom_point(), filename = "example2.jpeg") # Produces Figure 2
#
\begin{figure}
\centering
\includegraphics[width = 0.48\textwidth]{./example2}
\caption{Exponential Distribution based plots with points and lines.}
\label{fig2}
\end{figure}
\end{document}
and the pdf is build with the R commands
Sweave(file = 'example.Rnw',
engine = "R",
keep.source = 'TRUE',
echo = 'TRUE',
results = 'verbatim')
tools::texi2dvi(file = "example.tex",
pdf = TRUE,
clean = TRUE)
Any insight on how do this would be great.
Here is one way to solve this issue by redefining the Sinput environment in which source code is wrapped by Sweave. By default, it is a simple verbatim environment which is not processed by latex for tokens. The trick is to redefine it to use the alltt environment which allows some tokens to be parsed inside the alltt environment. Note that this might lead to unwanted side effects that I am not aware of, so use with caution!
Here is a reproducible example that works. If you compile it, you will generate a file where ref{fig1} is replaced by the figure number.
\documentclass{article}
\usepackage{Sweave}
\usepackage{alltt}
\renewenvironment{Sinput}{\begin{alltt}}{\end{alltt}}
\begin{document}
In this document, we will create a plot using `R`, and reference its position in
the source code.
<<produce-plot, results = hide>>=
pdf('example1.pdf')
plot(1:10, 1:10) # Produces Figure \ref{fig1}
dev.off()
#
\begin{figure}
\includegraphics{example1.pdf}
\caption{Figure 1}
\label{fig1}
\end{figure}
\end{document}