when knitting an Rmd file in RStudio Server, plot label fonts look terrible

I have an Rmd file (see below). When I knit it in RStudio Server, the plot label fonts look awful, like this:

image

If I knit it from the command line or from RStudio (desktop app), it works fine.

When knitting from RStudio Server I see the following warning which I suspect is part of the problem:

In grDevices::png(f) : unable to open connection to X11 display ''

Here is the .Rmd file:

    ---
    title: "test plotting"
    author: "Janet Young"
    output:
    html_document:
        toc: true
        toc_float:
        collapsed: false
        number_sections: true
        code_folding: hide
    ---


    ```{r setup, include=FALSE, echo=FALSE}
    library(ggplot2)
    library(knitr)
    library(Cairo)
    options(bitmapType="cairo")
    

    ```

    ```{r simple plot1, fig.height=4, fig.width=7}
    dat <- data.frame(samples=paste("sample",rep(1:10, 100), sep=""), count=rnorm(1000,1))

    ggplot(dat, aes(samples)) +
    geom_bar() +
    labs(title="total number of rows, all samples",
        x="", y = "number of rows") +
    theme(axis.text.x=element_text(angle = 90, hjust=1, vjust=0.5))

    ```

    ```{r simple plot2, fig.height=4, fig.width=7}
    plot(1:10,1:10, xlab="my x axis", ylab="my y axis")
    ```

    ```{r show dpi}
    dpi <- knitr::opts_chunk$get()$dpi
    cat("opts_chunk dpi is",dpi,"\n")
    ```

Things that need X11 in general and Cairo in particular do not work via RStudio Server unless you take special action. Any particular reason why you want to use Cairo?

1 Like

I used cairo because it was suggested as a way to solve this problem. I'm not wedded to it.

I found a workaround using the showtext package. It's not ideal for me, in that I'd prefer that the same Rmd file "just work" and knit both in RStudio Server and on systems with X11, without any changes, but that may be too much to ask for.

Have you tried removing

from your Rmd without any further changes? That works for me with identical results both locally (with X11) and on a server. From what I understand the suggestion to use Cairo is helpful when running a batch script, e.g. with Rscript. For R-markdown this seems to be unnecessary.

Yes, that is what I had originally when I ran into this problem. Adding those lines was the first attempt to solve the problem (which did not work).

I found a better (or at least simpler) solution, putting:

knitr::opts_chunk$set(dev="CairoPNG")

at the top of my first code chunk. It does require that Cairo be installed.
Got this suggestion from here.