so I've had this question for quite a while now and I have not found a solution to this. Whenever I want to label a parameter of interest, such as central tendencies (mean, median etc.), for example, I create a vertical and/or horizontal line and use annotate for the labeling. However, I have not been able to use LaTeX and non-hardcoded values concurrently. A MRE is shown below:
data <- data.frame(stat = rnorm(1000))
plot <-
ggplot(data, aes(x = stat)) +
geom_histogram(aes(y=..density..), fill="aquamarine", color="black") +
geom_density(color="black", size=1) +
geom_vline(xintercept = 0, color = "blue", linetype="dashed", size = 1) +
annotate("text", x=-0.2, y=0.2,
label=paste0("Mean = ", round(mean(data$stat), 4)),
angle=90, size=7, color="black")
plot
See figure here: https://i.sstatic.net/QzojQ.png
In the example above, I generate some random normal data, save it to a dataframe and plot it. I add a dashed vertical line corresponding to the mean of the data and then label it via annotate. Note, however, that I explicitly write Mean in the label since the LaTeX operators don't work and random letters are not ideal for me.
A solution I found is by using expression instead of paste0 when labeling as shown below:
data <- data.frame(stat = rnorm(1000))
plot <-
ggplot(data, aes(x = stat)) +
geom_histogram(aes(y=..density..), fill="aquamarine", color="black") +
geom_density(color="black", size=1) +
geom_vline(xintercept = 0, color = "blue", linetype="dashed", size = 1) +
annotate("text", x=-0.25, y=0.2, label = expression(mu ~ "= -0.0403"),
angle=90, size = 7, color = "black")
plot
See figure here: https://i.sstatic.net/rnW5i.png
This allows us to get the LaTeX characters, such as $\mu$ in our case, to show in the plot. But now the downside is that I have to hardcode the mean value in the expression field. This is not ideal and I don't want to do this. I want to be able to do something as follows but this doesn't work:
annotate("text", x=-0.25, y=0.2,
label = expression(mu ~ round(mean(data$stat), 4)),
angle=90, size = 7, color = "black")
I have not been able to find a solution to this so any help is greatly appreciated.
