rggplot2special-characterssave-asannotate

Symbol lambda (λ) is not showing up when exporting image as PDF in R?


I created a figure in R using ggplot2, and using annotate I included a lambda (λ) symbol in the text. However, when I do Export > Save as PDF, the PDF image does not show the lambda and instead just shows a ".." I have attached an example of what this looks like below:

enter image description here

This is the code I used:

dna.b.bae.coi <- data.frame(hours=c(1,2,24,48,96,168,672), copies=c(39,46,13,1,0,0,0))
nlsLM(copies ~ a*exp(b*hours), data=dna.b.bae.coi, start=list(a=39,b=-0.16507))
nlsplot(dna.b.bae.coi, model=6, start=c(a=45.97176,b=-0.05464))
a1<- ggplot(dna.b.bae.coi, aes(x=hours, y=copies)) + geom_point() + stat_smooth(method = 'nls', method.args = list(start = c(a=45.97176,b=-0.05464)), formula = y~a*exp(b*x), se=FALSE, linetype=2, colour="yellow") + theme_classic() + xlab("") + ylab("") + 
  annotate("text", x = 300, y = 46, label = "COI eDNA\nλ = -0.0546", color = "black", hjust = 0, vjust = 1) +
  ggtitle(expression(~italic("Baetidae")))
a1

I am not sure why this is happening. Is there a way around this so that the λ actually shows up in my Figure when I save as PDF?

Thanks in advance!


Solution

  • This works with ggsave:

    > p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + annotate("text", x = 300, y = 46, label = "COI eDNA\nλ = -0.0546", color = "black", hjust = 0.5, vjust = 1)
    > ggsave("pp.png")
    

    enter image description here


    EDIT With tikzDevice:

    To get a pdf, you can use tikzDevice, which converts your plot in LaTeX.

    library(tikzDevice)
    plot2tikz <- function(code, filename="Rplot", outdir=getwd(),
                          overwrite=FALSE, format="pdf", lua=FALSE,
                          packages=NULL, addDefaultTikZoptions=TRUE,
                          compile=TRUE, clean=FALSE, ...){
      format <- match.arg(format, choices = c("pdf", "ps", "eps"))
      texfile <- paste0(filename, ".tex")
      owd <- setwd(outdir); on.exit(setwd(owd))
      if(overwrite || !file.exists(texfile)){
        if(is.null(packages)){
          if(format=="pdf") packages <- getOption("tikzLatexPackages")
          if(format %in% c("ps", "eps")) packages <- c("\\thispagestyle{empty}\n", "\\usepackage{tikz}\n")
        } else {
          if(!"\\usepackage{tikz}\n" %in% packages){
            packages <- c("\\usepackage{tikz}\n", packages)
            if(format=="pdf" && addDefaultTikZoptions){
              packages <- union(packages, getOption("tikzLatexPackages"))
            }
          }
        }
        tikz(texfile, standAlone=TRUE, onefile=FALSE, packages=packages, ...)
        code()
        grDevices::dev.off()
      }
      if(compile || format=="eps"){
        message("Compilation...")
        if(format=="pdf"){
          # pdf compilation
          pdffile <- stringr::str_replace(texfile, ".tex", ".pdf")
          if(overwrite || !file.exists(pdffile)){
            if(lua){
              command <- sprintf("lualatex %s", texfile)
              system(command)
            }else{
              tools::texi2dvi(texfile, pdf=TRUE, clean=clean)
            }
            message(sprintf("Output pdf file: %s.pdf", filename))
          }
        } else if(format %in% c("ps", "eps")){
          psfile <- stringr::str_replace(texfile, ".tex", ".ps")
          if(overwrite || !file.exists(psfile)){
            tools::texi2dvi(texfile, pdf=FALSE, clean=clean)
            command <- sprintf("dvips %s.dvi", filename)
            system(command)
            message(sprintf("Output ps file: %s.ps", filename))
            if(format=="eps"){
              command <- sprintf("ps2epsi %s.ps %s.epi", filename, filename)
              system(command)
              file.rename(sprintf("%s.epi", filename), sprintf("%s.eps", filename))
              message(sprintf("Output eps file: %s.eps", filename))
            }
          }
        }
      }
      #
      message(sprintf("Output tex file: %s", normalizePath(texfile, winslash=.Platform$file.sep)))
      return(invisible())
    }
    
    
    library(ggplot2)
    plotCode <- function(){
      gg <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + 
        annotate("text", x = 300, y = 46, label = "COI eDNA\n$\\lambda$ = -0.0546", 
                 color = "black", hjust = 0.5, vjust = 1)
      print(gg)
    }
    
    
    plot2tikz(plotCode, compile=FALSE, outdir=getwd(), overwrite = TRUE,
              packages=c("\\usepackage[active,tightpage,psfixbb]{preview}\n",
                         "\\PreviewEnvironment{pgfpicture}\n",
                         "\\setlength\\PreviewBorder{10pt}\n",
                         "\\usepackage{amssymb}\n"),
              documentDeclaration ="\\documentclass[12pt]{standalone}\n",
              width=7, height=5)
    

    enter image description here