Search code examples
rplotplotmath

R: plotmath expression symbols not showing up in interaction plot


For some reason, my interaction plots don't seem to show the greek symbols (latex) in R markdown (using R studio). The code I am using is reproduced below. Why are the expression() functions not working? Any suggestions?

with(ba_results, interaction.plot(as.factor(f1), as.factor(f2), 
                                  y,
                                  type = "b",
                                  pch = c(18, 19, 24),
                                  fixed = TRUE,
                                  xlab = "Scale factor",
                                  ylab = "Mean Response",
                                  trace.label = expression(mu_e),
                                  main = paste("Interaction plot of", 
                                               expression(mu[e]), 
                                               "f1")))

Solution

  • For the title, wrap the whole thing in expression. For example, main = expression(paste("Interaction plot of ", mu[e], " f1")) or main = expression(Interaction~plot~of~mu[e]~f1).

    For the trace.label, the expression is not being parsed properly. It looks like the problem is this line in the code for interaction.plot:

    text(xleg, ylim[2L] - 0.05 * yrng, paste("  ", trace.label), adj = 0)
    

    So trace.label is wrapped in paste which turns the expression back into a text string. For example:

    expression(mu[e])
    # expression(mu[e])
    
    paste("  ", expression(mu[e]))
    # "   mu[e]"
    

    As a workaround, you can modify the function to use trace.label as is. To do that, get the code for interaction.plot by typing interaction.plot in the console. Copy the code into a new R script file and assign the function a new name like my_interaction_plot. Then change the line above to this:

    text(xleg, ylim[2L] - 0.05 * yrng, trace.label, adj = 0)
    

    This change will result in expression(mu[e]) being parsed properly.

    Now just use my_interaction_plot instead of interaction.plot like this:

    with(ba_results, 
         my_interaction_plot(as.factor(f1), as.factor(f2), y, type = "b",
                             pch = c(18, 19, 24), fixed = TRUE,
                             xlab = "Scale factor", ylab = "Mean Response",
                             trace.label = expression(mu_e),
                             main = expression(paste("Interaction plot of ", mu[e], " f1"))))