1

I have an knitr document with single plot. I want to use the original fonts of R in the plot except the axis labels which should come from latin modern. I can use latin modern for all the fonts in the plot by tikzDevice package of R. But compiling this takes too much time when the data set used for plotting is very big.

OR, Can I use tikzDevice only for labels and title of the plot?

A summary code is below:

<<setup, include=FALSE, cache=FALSE>>=
library(knitr)
library(tikzDevice)
#opts_chunk$set(dev = 'tikz') # I don't want to use tikzDevice.
opts_chunk$set(dev.args=list(pointsize=12)) 
@

<<tikzfigure, echo = FALSE, fig.width = 4, fig.height = 4, fig.align = 'center', fig.pos = 'ht', tidy = TRUE>>=

plot(1:5,1:5,xlab=paste0("$\\sum \\beta_i$"))
@

The output:

enter image description here

The plot should stay as the same except the x label should be

enter image description here

(latin modern font.)

How can I achieve this?

(Note: I asked the question stackoverflow as well, but I think this is the correct place for it. I don't know if this is a problem...)

2
3

You can use the latex2exp library to parse the LaTeX code in your label. Make sure you have a font that contains the italic beta. I used I used CM-Unicode. You can access the glyph using the unicode representation \u03B2 or as the character β.

Here is a complete MWE in knitr (.Rnw file):

\documentclass[border=3pt]{standalone}

<<setup, include=FALSE, cache=FALSE>>=
rm(list = ls())
library(knitr)
library(latex2exp)
library(showtext)
font_add("CMUSerif-RomanSlanted",regular="c:/windows/fonts/cmunsl_0.ttf")
#library(tikzDevice)
#opts_chunk$set(dev = 'tikz') # I don't want to use tikzDevice.
opts_chunk$set(dev.args=list(pointsize=12))
@

\begin{document}
<<chunk1, echo = FALSE, fig.width = 4, fig.height = 4>>=
plot(1:5,1:5,xlab=TeX("$\\sum \\textit{\u03B2_i}$"))
plot(1:5,1:5,xlab=TeX("$\\sum \\textit{\u03B2_i}$",list(family="CMUSerif-RomanSlanted")))
plot(1:5,1:5,xlab=TeX("$\\sum \\textit{β_i}$",list(family="CMUSerif-RomanSlanted")))
@
\end{document}

Giving this:

enter image description here

2
  • 1
    Ross (+1) Thanks for the response. Actually I know this approach but I would like to get latin modern math fonts (upright digits, italic letters etc.) on the labels. – mert Jun 21 '20 at 14:31
  • @mert. I updated with the italic beta. – Ross Jun 22 '20 at 2:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.