ggplot2 image not showing up in pdf from Rmd - r

Sort of new to R markdown. I define a function that makes a plot with ggplot2 in a separate .R file:
heatMapDevRatio <- function(glmnet_obj_list,alpha_seq,
plot_name){
grid <- matrix(NA,nr=1,ncol=3)
colnames(grid) = c('alpha','lambda','dev.ratio')
for(idx in 1:length(glmnet_obj_list)){
alpha = getAlpha(names(glmnet_obj_list)[idx])
temp_df = data.frame(alpha=alpha,
lambda=glmnet_obj_list[[idx]]$lambda,
dev.ratio=glmnet_obj_list[[idx]]$dev.ratio)
grid = rbind(grid,temp_df)
}
grid = grid[-1,]
ggplot(data = grid, aes(lambda, alpha)) +
geom_raster(aes(fill = dev.ratio), interpolate = TRUE) +
ggtitle(plot_name) +
xlab(expression(~lambda)) +
ylab(expression(~alpha))
}
Anyway, the function runs fine-- the output goes to the standard graphics device if I run it in interactive session, or wherever I direct it if use the function in a script.
The problem is when I run the function in an Rmd file after source()-ing the file with the function definition.
```{r heatmap 10yr,eval=T,echo=F,fig.height=4,fig.width=4,fig.cap='lkjafkd'}
heatMapDevRatio(fitted_mods_20yr[2:10],alpha_seq,'adfasfd')
```
The export to pdf works, but on the pdf I just have a reference to some weird directory that doesn't seem to exist after execution-- where the figure should be, I have this text:
![lkjafkd](cox_summary[exported]_files/figure-latex/heatmap 10yr-1.pdf)
Should I just write the image to a file and include it, or should I be redirecting the graphics output? I thought it should just work.
Do you think the problem is the command I'm using to weave?
Rscript -e "rmarkdown::render('cox_summary.Rmd', output_format = 'pdf_document', output_file = 'cox_summary[exported].pdf')"

Related

How to send output plot from 'checkresiduals() function to a pdf file

I am wondering if there is a way to send the output plot from the checkresiduals() function to a pdf file.
I have the following command :-
checkresiduals(ts_regr_auto_new_objects[[1]], test = FALSE, plot = TRUE)
This generates a series of plots including ACF plot, residual density plot and the residual plot.
Will try and attach the image - for some reason its not doing it now but hopefully can reproduce the image again later.
The image is attached now :-
I can save the save the image as a pdf file from the RStudio console but I would like to be able to do so from code as this is a part of a larger application code.
Best regards
Deepak
I'm not familiar with checkresiduals, but generally it should be possible to save PDF with base R:
# start PDF output
pdf(file = "plot.pdf", paper = "a4")
# some graphics
hist(rnorm(100))
# end of output, save file
dev.off()
So for your case probably this:
pdf(file = "plot.pdf", paper = "a4")
checkresiduals(ts_regr_auto_new_objects[[1]], test = FALSE, plot = TRUE)
dev.off()
See documentation... Hope this helps.

ggplot2 does not show the graph in Latex (knitr)

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.

Task Schedular Giving Error while scheduling R Script for saving PDF

I am scheduling R script which contains ggsave for saving pdf.
my code is running but on the line of ggsave("plot.pdf), it is skipping code. But instead of saving pdf if i use png format then it is fine. but only for pdf it is giving problem.
Below is my sample code.
library(ggplot2)
library(data.table)
a <- data.frame(a = c(1:5))
p <- ggplot(data.frame(x = 1:5, y = 1:5), aes(x, y)) + geom_point()
fwrite(a,"abc1.csv")
ggsave("plot.pdf")
Does ggsave(p, "plot.pdf", device = "pdf") work? You may not have been specifying the plot to be saved or perhaps it doesn't know to export as pdf from only the file path that you gave?
EDIT: It should be ggsave("plot.pdf", p, device = "pdf") so that the arguments are in the correct order.

Modify external R script in a knitr chunk

I'm wondering if it's possible to hook into the code in an external R script that is read by knitr.
Specifically, say that you have the following R file
test.R
## ---- CarPlot
library(ggplot2)
CarPlot <- ggplot() +
stat_summary(data = mtcars,
aes(x = factor(gear),
y = mpg
),
fun.y = "mean",
geom = "bar"
)
CarPlot
Imagine that you wanted to use this graph in multiple reports, but in one of these reports you want the graph to have a title and in the other report you do not.
Ideally, I would like to be able to use the same external R script to be able to do this so that I do not have to make changes to multiple R files in case I decide to change something about the graph.
I thought that one way to perhaps do this would be by setting the fig.show chunk option to hold—since it will "hold all plots and output them in the very end of a code chunk"—and then appending a title to the plot like so:
test.Rnw
\documentclass{article}
\begin{document}
<<external-code, cache=FALSE,echo=FALSE>>=
read_chunk('./test.R')
#
<<CarPlot,echo=FALSE,fig.show='hold'>>=
CarPlot <- CarPlot + ggtitle("Plot about cars")
#
\end{document}
This, however, does not work. Although the plot is printed, the title that I tried to append does not show up.
Is there some way to do what I would like to do?
You don't want to show the plot created by test.R, so you should set fig.show = 'hide' or include = FALSE for that chunk:
<<external-code, cache=FALSE,echo=FALSE,fig.show = 'hide'>>=
read_chunk('./test.R')
#
You do want to show the plot after modification, so you have to print it:
<<CarPlot,echo=FALSE>>=
CarPlot <- CarPlot + ggtitle("Plot about cars")
CarPlot
#
fig.show = 'hold' is used if you have a large code chunk that prints a plot in the middle, but you don't want the plot to show in your document until the end. It doesn't apply to this case.

Dynamic references to figures in a R comment within Sweave document

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}

Resources