Search code examples
rggplot2labellatexconcatenation

Concat math symbols and strings in ggplot2 labels - R, LaTex Solution?


I am trying to label the y-axis of my graph with the Theta greek symbol and P(z) with a comma separating them. Additionally, I am tyring to label my x-axis Q(z_i) where i is a subscript. I have tried to do this a few different ways..

string <- ", P(z)"
thet <- bquote(theta)
ylab.fig2 <- paste(thet, string, sep = "")

and have done something similar with expression(theta). I use ylab.fig2 as an input in my ggplot, ylab(fig.2).

new <- ggplot(data = data.frame(x=0), aes(x=x)) + 
  stat_function(fun=Pz.eq, aes(colour="P(z)")) +
  stat_function(fun=bid1, aes(colour="Bid Curve: House 1")) +
  stat_function(fun=bid2, aes(colour="Bid Curve: House 2")) +
  stat_function(fun=bid3, aes(colour="Bid Curve: House 3")) +
  xlim(0,20) + ylim(0,6) +
  xlab("Q(z_i)") + ylab(ylab.fig2) +
  ggtitle("Figure 2: Property Choice Per Household") +
  theme(panel.grid = element_blank(),
        axis.text.x = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.x = element_blank(),
        axis.ticks.y = element_blank(),
        legend.title = element_blank(),
        plot.title = element_text(hjust=0.5)) +
  scale_colour_manual("Groups", 
                      values = c("darkseagreen", "darkkhaki", "darkslategray3", "firebrick")) 

The bquote() and expression() both work fine if they are sole inputs but when I use paste to return the rest of the axis label the greek symbol is not output. I believe this is due to the differing class() of each object. Alternatively, if there is a way to compile LaTex in the labels that would solve both my x and y-axis issues.

This is what my graph looks like thus far... enter image description here

Overall, there are three things I'm trying to accomplish with x and y-axis labels: 1) Concat greek letters with text. 2) Put bold text inside of the label (only the z vector in P(z) will be bold). 3) Place 'i' subscripts on my text.

While the question regarding Greek letters has been posted before I am looking for a solution using LaTex where I can use more than just math symbols. Using LaTex code is will allow me to solve issues 2 and 3, not just 1.


Solution

  • The latex2exp package is probably the easiest:

    library(latex2exp)
    string <- ", P(z)"
    thet <- "$\\theta$"
    ylab.fig2 <- TeX(paste(thet, string, sep = ""))
    

    And then use as ... + ylab(ylab.fig2) to build the plot.