Reputation: 7043
Gnu R ships with a very odd way to note formulas and symbols. It is often discussed here and mentioned in the R helppage ?plotmath
. For anyone who ever wrote LaTeX
the code for a simple formula in R looks unreadable and is errorprone to write.
Is there a better way to annotate with formulas? Is there a function like tex2r("x_2")
that will generate the strange code?
I am looking for a solution without TikZdevice, because TikZdevice is still very fragile and the printoout does not look exactly the same.
Upvotes: 2
Views: 5813
Reputation: 348
I just found a package that does exactly what OP was asking for: latex2exp
and in there the fuction TeX
.
E.g.:
library(latex2exp)
library(berryFunctions)
set.seed(1)
milk <- data.frame(Datum = as.Date(rep(seq(17500, 18460, by = 30), each = 30), origin = "1970-01-01"),
Milch = abs(rnorm(990, mean = 20, sd = 8)))
X11(width = 12, height = 7)
par(mar = c(3,5.5,3,1))
with(milk, plot(Datum, Milch, pch = "-", cex=1.5, col = rgb(red = 0, green = 0.5, blue = 0.5, alpha = 0.7),
xaxt = "n", xlab = "", ylab = "",
main = "Milchleistung am Wolkenhof"))
title(ylab = TeX("Milchmenge $\\,$ $\\left[\\frac{\\mathrm{kg}}{\\mathrm{Kuh} \\cdot \\mathrm{Tag}}\\right]$"), line = 2.5)
monthAxis()
yields:
Edit: Now there is a space between "Milchmenge" and the left bracket "[", but I didn't want to upload a new picture therefore.
Upvotes: 1
Reputation: 162431
With the tikzDevice package (currently available only from the CRAN archive) you can use straight-up LaTeX markup to annotate your plots. (The package comes with a beautiful vignette that'll get you up and running).
The example below was lifted directly from this page, which also displays the figure it produces:
require(tikzDevice)
tikz('normal.tex', standAlone = TRUE, width=5, height=5)
# Normal distribution curve
x <- seq(-4.5,4.5,length.out=100)
y <- dnorm(x)
# Integration points
xi <- seq(-2,2,length.out=30)
yi <- dnorm(xi)
# plot the curve
plot(x,y,type='l',col='blue',ylab='$p(x)$',xlab='$x$')
# plot the panels
lines(xi,yi,type='s')
lines(range(xi),c(0,0))
lines(xi,yi,type='h')
#Add some equations as labels
title(main="$p(x)=\\frac{1}{\\sqrt{2\\pi}}e^{-\\frac{x^2}{2}}$")
int <- integrate(dnorm,min(xi),max(xi),subdivisions=length(xi))
text(2.8, 0.3, paste("\\small$\\displaystyle\\int_{", min(xi),
"}^{", max(xi), "}p(x)dx\\approx", round(int[['value']],3),
'$', sep=''))
#Close the device
dev.off()
# Compile the tex file
tools::texi2dvi('normal.tex',pdf=T)
Upvotes: 7