stephanmg
stephanmg

Reputation: 766

Tikz output with GNU R with special Latex characters and ggplot2

Frequently I need to save a plot as TIKZ and as a PNG after creating a plot with ggplot2 in GNU R.

Special LaTeX characters have to be escaped in the legend or axis title. If I save the two plots, then I will end up with garbage in the PNG output (Example 1) or TIKZ won't be outputted if special characters are not escaped (Example 2).

Obvious solution is to have a conditional to decide how to format (escape or not escape) the subtitle. How to avoid code duplication here?

Example 1:

attach(all)
p <- ggplot(data = all, aes(x = Time, y = Concentration, color = Status)) + geom_line() + geom_point()
p <- p + labs(subtitle="50\\% reduction")
ggsave(filename="test.png")
detach(all)

tikz(file=paste(sub('\\.[^\\.]*$', '', outputname), ".tex", sep=""))

Example 2:

attach(all)
p <- ggplot(data = all, aes(x = Time, y = Concentration, color = Status)) + geom_line() + geom_point()
p <- p + labs(subtitle="50% reduction")
ggsave(filename="test.png")
detach(all)

tikz(file=paste(sub('\\.[^\\.]*$', '', outputname), ".tex", sep=""))

Upvotes: 1

Views: 243

Answers (1)

user2554330
user2554330

Reputation: 44877

You should write a function to handle this. You don't say how you are deciding whether to output TIKZ vs PNG, but I'll assume you can produce a boolean tikz to describe the decision. Then add your subtitle like this:

escapeIfTikz <- function(s, tikz = ...) {
  if (tikz)
    gsub("([$%])", "\\\\\\1", s)  # add other necessary escapes
  else
    s # Do nothing for PNG
}

p <- p + labs(subtitle=escapeIfTikz("50% reduction"))

Upvotes: 1

Related Questions