I'm working with a large collection of R Markdown files that are collectively used to create a book (PDF output) using bookdown. For long lines of code (that will show up in the book), I've been writing it out close to column 80, at which point I insert a hard line break, tab (4 spaces) over, and continue the code. This is what I think looks good in the text (for readers). However, I'm running into problems when this is (for example) part of a ggplot() function. Here's a quick (meaningless) example:
testx <- seq(1:100)
testy <- rnorm(testx)
testdat <- as.data.frame(cbind(testx, testy))
g <- ggplot(testdat, aes(x = testx/100, y = testy))
g <- g + geom_point() + geom_line()
g <- g + labs(title = "The Posterior Distribution",
caption = "The mode and 95% HPD intervals are the dot and horizontal line at
the bottom, respectively.",
x = expression(beta[1]~(slope)))
g
In this example, I need to break the caption() argument across two lines because it is long, but I do NOT want it to break in the actual caption.
Is there a way to do this?
If I understood correctly, you can use paste0.
caption = paste0("The mode and 95% HPD intervals are the dot",
" and horizontal line at the bottom, respectively.")
I'm plotting photosynthetically active radiation which has units of umol/m2/s
I can get R to plot "PAR umol m-2" with the u as mu and -2 in superscript using:
bp_m + ylab(expression(paste('PAR ',mu,'mol m')^-2))
where bpm is the rest of the plot, but I can't get it to add the s^-1, I've tried various forms of expressions, paste etc
Finally got there - R seems to have so many different ways of doing the same thing, taking me ages to get my head around the syntax etc
bp_m+labs(y = ~paste("PAR ", mu, "mol m"^-2,"s"^-1))
bp_m+ylab(~paste("PAR ", mu, "mol m"^-2,"s"^-1)))
both work
I was wondering how I can paste the following equation as legend or text box to my plot in R (shown below in Latex format):
$$
x_i\stackrel{{\rm iid}}{\sim}{\rm Normal}\big(\mu-\frac \alpha 2,\sigma^2\big),\quad i = 1,\ldots, N_x \\
y_i\stackrel{{\rm iid}}{\sim}{\rm Normal}\big(\mu+\frac \alpha 2,\sigma^2\big),\quad i = 1,\ldots, N_y
$$
You can try the following
library(latex2exp)
plot(TeX("$x_i$ \t $\\overset{iid}{\\sim}$ \t $Normal$
$\\left(\\mu -\\frac{\\alpha}{2} ,\\sigma^2\\right)$,\t$i = 1,\\ldots, N_x$"))
to get the following
I would like to add LaTeX typesetting to elements of plots in R (e.g: the title, axis labels, annotations, etc.) using either the combination of base/lattice or with ggplot2.
Questions:
Is there a way to get LaTeX into plots using these packages, and if so, how is it done?
If not, are there additional packages needed to accomplish this.
For example, in Python matplotlib compiles LaTeX via the text.usetex packages as discussed here: http://www.scipy.org/Cookbook/Matplotlib/UsingTex
Is there a similar process by which such plots can be generated in R?
The CRAN package latex2exp contains a TeX function that translate LaTeX formulas to R's plotmath expressions. You can use it anywhere you could enter mathematical annotations, such as axis labels, legend labels, and general text.
For example:
x <- seq(0, 4, length.out=100)
alpha <- 1:5
plot(x, xlim=c(0, 4), ylim=c(0, 10),
xlab='x', ylab=TeX(r'($\alpha x^\alpha$, where $\alpha \in \{1 \ldots 5\}$)'),
type='n', main=TeX(r'(Using $\LaTeX$ for plotting in base graphics!)', bold=TRUE))
for (a in alpha) {
lines(x, a*x^a, col=a)
}
legend('topleft',
legend=TeX(sprintf(r'($\alpha = %d$)', alpha)),
lwd=1,
col=alpha)
produces this plot.
Here's an example using ggplot2:
q <- qplot(cty, hwy, data = mpg, colour = displ)
q + xlab(expression(beta +frac(miles, gallon)))
As stolen from here, the following command correctly uses LaTeX to draw the title:
plot(1, main=expression(beta[1]))
See ?plotmath for more details.
You can generate tikz code from R:
http://r-forge.r-project.org/projects/tikzdevice/
Here's something from my own Lab Reports.
tickzDevice exports tikz images for LaTeX
Note, that in certain cases "\\" becomes "\" and "$" becomes "$\" as in the following R code: "$z\\frac{a}{b}$" -> "$\z\frac{a}{b}$\"
Also xtable exports tables to latex code
The code:
library(reshape2)
library(plyr)
library(ggplot2)
library(systemfit)
library(xtable)
require(graphics)
require(tikzDevice)
setwd("~/DataFolder/")
Lab5p9 <- read.csv (file="~/DataFolder/Lab5part9.csv", comment.char="#")
AR <- subset(Lab5p9,Region == "Forward.Active")
# make sure the data names aren't already in latex format, it interferes with the ggplot ~ # tikzDecice combo
colnames(AR) <- c("$V_{BB}[V]$", "$V_{RB}[V]$" , "$V_{RC}[V]$" , "$I_B[\\mu A]$" , "IC" , "$V_{BE}[V]$" , "$V_{CE}[V]$" , "beta" , "$I_E[mA]$")
# make sure the working directory is where you want your tikz file to go
setwd("~/TexImageFolder/")
# export plot as a .tex file in the tikz format
tikz('betaplot.tex', width = 6,height = 3.5,pointsize = 12) #define plot name size and font size
#define plot margin widths
par(mar=c(3,5,3,5)) # The syntax is mar=c(bottom, left, top, right).
ggplot(AR, aes(x=IC, y=beta)) + # define data set
geom_point(colour="#000000",size=1.5) + # use points
geom_smooth(method=loess,span=2) + # use smooth
theme_bw() + # no grey background
xlab("$I_C[mA]$") + # x axis label in latex format
ylab ("$\\beta$") + # y axis label in latex format
theme(axis.title.y=element_text(angle=0)) + # rotate y axis label
theme(axis.title.x=element_text(vjust=-0.5)) + # adjust x axis label down
theme(axis.title.y=element_text(hjust=-0.5)) + # adjust y axis lable left
theme(panel.grid.major=element_line(colour="grey80", size=0.5)) +# major grid color
theme(panel.grid.minor=element_line(colour="grey95", size=0.4)) +# minor grid color
scale_x_continuous(minor_breaks=seq(0,9.5,by=0.5)) +# adjust x minor grid spacing
scale_y_continuous(minor_breaks=seq(170,185,by=0.5)) + # adjust y minor grid spacing
theme(panel.border=element_rect(colour="black",size=.75))# border color and size
dev.off() # export file and exit tikzDevice function
Here's a cool function that lets you use the plotmath functionality, but with the expressions stored as objects of the character mode. This lets you manipulate them programmatically using paste or regular expression functions. I don't use ggplot, but it should work there as well:
express <- function(char.expressions){
return(parse(text=paste(char.expressions,collapse=";")))
}
par(mar=c(6,6,1,1))
plot(0,0,xlim=sym(),ylim=sym(),xaxt="n",yaxt="n",mgp=c(4,0.2,0),
xlab="axis(1,(-9:9)/10,tick.labels,las=2,cex.axis=0.8)",
ylab="axis(2,(-9:9)/10,express(tick.labels),las=1,cex.axis=0.8)")
tick.labels <- paste("x >=",(-9:9)/10)
# this is what you get if you just use tick.labels the regular way:
axis(1,(-9:9)/10,tick.labels,las=2,cex.axis=0.8)
# but if you express() them... voila!
axis(2,(-9:9)/10,express(tick.labels),las=1,cex.axis=0.8)
I did this a few years ago by outputting to a .fig format instead of directly to a .pdf; you write the titles including the latex code and use fig2ps or fig2pdf to create the final graphic file. The setup I had to do this broke with R 2.5; if I had to do it again I'd look into tikz instead, but am including this here anyway as another potential option.
My notes on how I did it using Sweave are here: http://www.stat.umn.edu/~arendahl/computing
I just have a workaround. One may first generate an eps file, then convert it back to pgf using the tool eps2pgf. See http://www.texample.net/tikz/examples/eps2pgf/
h <- rnorm(mean = 5, sd = 1, n = 1000)
hist(h, main = expression(paste("Sampled values, ", mu, "=5, ", sigma,
"=1")))
Taken from a very help article here https://stats.idre.ucla.edu/r/codefragments/greek_letters/
You can use the following, for example:
title(sub=TeX(sprintf(paste("Some latex symbols are ", r'(\lambda)', "and", r'(\alpha)'))))
Just remember to enclose LaTeX expressions in paste() using r'()'
You can also add named objects in the paste() function. E.g.,
lambda_variable <- 3
title(sub=TeX(sprintf(paste(r'(\lambda=)', lambda_variable))))
Not sure if there are better ways to do this, but the above worked for me :)
I'd like to create latex-style math in plot titles in R. The plotmath tools have a useful but limited subset of expressions they can display, and use non-latex syntax and style.
For instance, I would like to print the equation $\mathrm{d} \mathbf{x} = a [\theta - \mathbf{x}] \mathrm{d} t$ in the title of the plot, and still evaluate the value of certain variables. The best solution I have is the very cumbersome:
lambda <- 4
plot(1:10,1:10)
mtext(bquote(paste(d*bolditalic(x)[italic(t)] == alpha*(theta - bolditalic(x)[italic(t)] )*d*italic(t) + .(lambda) * d * italic(B)[italic(t)] )), line=2.25,cex=2)
or
require(ggplot2)
qplot(1:10, 1:10) + opts(title=bquote(paste(d*bolditalic(x)[italic(t)] == alpha*(theta - bolditalic(x)[italic(t)] )*d*italic(t) + .(lambda) * d * italic(B)[italic(t)] )), line=2.25,cex=2)
This question almost solves this, but I loose the ability of bquote to display the numerical value of a variable (lambda in my example). Is there a way to combine these so I can have italic greek letters (the standard format for variables, e.g. as done by tex) and evaluate at specific values?
Is there a much better way where I can simple write tex-syntax for equations and add them to my graphs?
You may want to check out the tikzDevice package (or take a look at its vignette first), which provides a natural way to write LaTeX math in R graphics.
I also have a simple example here.
And here is another example:
library(tikzDevice)
library(ggplot2)
tikz('math.tex', standAlone = TRUE, width = 4, height = 4)
qplot(1:10, 1:10,
main = '$\\mathrm{d} \\mathbf{x} = a [\\theta - \\mathbf{x}] \\mathrm{d} t$')
dev.off()
which produces this if you run pdflatex math.tex:
You should edit your question rather than putting sub-comments (I'll see what I can do about the box.). I sometimes find that bquote only reaches down so deep and that you need to use substitute. This works:
lambda <- 4
plot(1:10,1:10)
mtext(substitute(paste(d*bolditalic(x)[italic(t)] ==
alpha*group("[", (theta - bolditalic(x)[italic(t)] )*d*italic(t) +
lambda, "]") * d * italic(B)[italic(t)] ), list(lambda=lambda)),
line=2.25,cex=2)
It also works with ggplot and the title placement looks a lot better:
qplot(1:10, 1:10) + opts(title=substitute(paste(d*bolditalic(x)[italic(t)] ==
alpha*(theta - bolditalic(x)[italic(t)] )*d*italic(t) +
lambda * d * italic(B)[italic(t)] ), list(lambda=lambda)),
line=2.25,cex=2)
The "d" is "square" at least as I understand your meaning after referring to a set of Latex examples online at:
http://www.personal.ceu.hu/tex/cookbook.html
(I thought you wanted the http://en.wikipedia.org/wiki/D%27Alembert_operator and was not able to find that yet.)