#' Save ggplot Figure to TeX Snippet
#'
#' @description
#' Creates two files (.tex and .png); the .png file contains the figure (ggplot)
#' that is submitted and the .tex file contains the snipped to load the figure
#' use (\\input{file.tex} in your TeX document) to include the figure with the
#' caption.
#'
#' @param g figure of class ggplot
#' @param fileGraph file name to save figure
#' @param caption caption for figure
#' @param ... parameters passed to ggsave() such as dpi,width
#'
#' @importFrom ggplot2 ggsave ggplot geom_point aes theme_bw
#' @importFrom tools file_ext
#'
#' @seealso \code{\link{raw.texArticle}}
#' @author Thomas Gredig
#'
#' @examples
#' q = tempdir()
#' x=seq(-10,10,0.1); y=x^2-2
#' g = ggplot2::ggplot(data.frame(x,y), ggplot2::aes(x,y)) +
#' ggplot2::geom_point(col='red') + ggplot2::theme_bw()
#' fig2tex(g, file.path(q,"test.png"), "First Graph.")
#'
#' @export
fig2tex <- function(g, fileGraph, caption, ...) {
if (!length(grep('ggplot',class(g)))>0) stop("Graph needs to be a ggplot object.")
# callerString = paste(traceback(), collapse=" - ")
ggsave(fileGraph, plot=g, ...)
fileTeX = gsub(file_ext(fileGraph),'tex',fileGraph)
label = gsub(file_ext(fileGraph),'',basename(fileGraph))
label = gsub('\\.','',label)
texBase = paste0("% AUTOGENERATED with RAWdataR::fig2tex()
% path: ",getwd(),"
% date: ",date(),"
%
\\begin{figure}[htbp]
\\centering % requires the graphicx package
\\includegraphics[width=0.95\\columnwidth]{",basename(fileGraph),"}
\\caption{", caption, "}
\\label{fig:", label, "}
\\end{figure}
")
fileConn<-file(fileTeX,"wt")
writeLines(texBase, fileConn)
close(fileConn)
fileTeX
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.