Tikz输出带有特殊Latex字符和ggplot2的GNU R



在GNU R.中使用ggplot2创建绘图后,我经常需要将绘图保存为TIKZ和PNG

特殊的LaTeX字符必须在图例或轴标题中转义。如果我保存了这两个图,那么我将在PNG输出中出现垃圾(示例1(,或者如果没有转义特殊字符,则不会输出TIKZ(示例2(。

显而易见的解决方案是有一个条件来决定如何格式化(转义或不转义(字幕。如何避免这里的代码重复?

示例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=""))

示例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=""))

您应该编写一个函数来处理此问题。您没有说明如何决定是否输出TIKZ与PNG,但我假设您可以生成一个布尔tikz来描述该决定。然后添加这样的副标题:

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"))

最新更新