Saïd Maanan
Saïd Maanan

Reputation: 687

How to Display LaTeX-style Expressions in R Plot Titles Using expression()

I am working on a simulation study in R where I am plotting bias and variance curves for different estimators. I want the titles of the subplots to include properly formatted mathematical expressions, specifically \beta_0, using expression() in the main argument of the plot() function. Here is a minimal working example:

# Define plotting parameters
coeff_labels <- c(expression(beta[0]), expression(beta[1]))
plot_titles <- c("Bias Curves", "Variance Curves")

# Attempting to plot with combined text and expressions
plot(NULL, xlim = c(1, 10), ylim = c(1, 10), 
     main = paste(plot_titles[1], " (", coeff_labels[1], ")", sep = ""))    

Instead of displaying the mathematical expression \beta_0 in the plot titles, the main text shows beta[0] as plain text.

Question:

How can I correctly format the plot titles to include both text (e.g., "Bias Curves") and LaTeX-style mathematical expressions like \beta_0​ and \beta_1​ in the main argument of plot()? Any suggestions or alternative approaches would be greatly appreciated.

Upvotes: 1

Views: 69

Answers (2)

user2554330
user2554330

Reputation: 44937

Your coeff_labels variables are expressions which would be formatted properly on their own, but you are combining them with strings using c(), so everything is converted to strings and it doesn't work.

If you were willing to hard code the labels, it would be easy. Use

# Attempting to plot with combined text and expressions
plot(NULL, xlim = c(1, 10), ylim = c(1, 10), 
 main = expression(paste("Bias Curves (", beta[0], ")")))

So the thing you need to do is to construct an expression like that out of variables. There are lots of ways to do it; substitute might be easiest. For example,

plot(NULL, xlim = c(1, 10), ylim = c(1, 10), 
 main = substitute(paste(title, " ", (label)), 
          list(title = plot_titles[1], 
               label = coeff_labels[[1]])))

Upvotes: 2

Carl Witthoft
Carl Witthoft

Reputation: 21532

Might be easier to work with grDevices:plotMath . Quoting,

If the text argument to one of the text-drawing functions (text, mtext, axis, legend) in R is an expression, the argument is interpreted as a mathematical expression and the output will be formatted according to TeX-like rules. Expressions can also be used for titles, subtitles and x- and y-axis labels (but not for axis labels on persp plots).

In most cases other language objects (names and calls, including formulas) are coerced to expressions and so can also be used.

Upvotes: 1

Related Questions