Skip to content

Instantly share code, notes, and snippets.

@mg98
Last active August 4, 2025 09:42
Show Gist options
  • Save mg98/5b6d7a90ea0c252b08840a408f2d3930 to your computer and use it in GitHub Desktop.
Save mg98/5b6d7a90ea0c252b08840a408f2d3930 to your computer and use it in GitHub Desktop.
Rscript for printing plot in LaTeX/tikz
library(tidyverse)
library(tikzDevice)
library(RColorBrewer)
print_plot <- function(plot, name, width=3.5, height=2.5){
tex_name <- sprintf("results/fig/%s.tex", name)
png_name <- sprintf("results/fig/%s.png", name)
tex_width <- width; tex_height <- height
png_width <- tex_width * 4; png_height <- tex_height * 4
# Define LaTeX preamble to use sans-serif font
sans_preamble <- c(
"\\usepackage{pgfplots}",
"\\pgfplotsset{compat=newest}",
"\\usepackage[utf8]{inputenc}",
"\\usepackage[T1]{fontenc}",
"\\usepackage{sfmath}", # Use sfmath for sans-serif math
"\\renewcommand{\\familydefault}{\\sfdefault}" # Set default font to sans-serif
)
# Use tikzDevice with custom preamble
tikz(file = tex_name, width = tex_width, height = tex_height, sanitize = TRUE,
documentDeclaration = "\\documentclass[12pt]{standalone}",
packages = sans_preamble)
print(plot)
dev.off()
# PNG export remains unchanged
png(file = png_name, width = png_width, height = png_height, units = "cm", res = 150)
print(plot)
dev.off()
}
\usepackage{pgfplots}
\pgfplotsset{every axis/.append style={font=\sffamily}}
\pgfplotsset{every axis label/.append style={font=\sffamily}}
\pgfplotsset{every tick label/.append style={font=\sffamily}}
\tikzset{every picture/.style={/utils/exec=\sffamily}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment