Miri
Miri

Reputation: 75

How to parse LaTeX math formulas within geom_text() of ggplot2

I want to add a geom_text() including a Latex formula to the plot, to describe the mean percentage of each value in the 2 matrices:

library(latex2exp)
library(ggplot2)
library(tidyverse)


percentage <- matrix(c(10,100,90,80,100,97,80,19,90,82,9,87),nrow=2)
colnames(percentage) <- c("value1","value2","value3","value4","value5","value6")
rownames(percentage) <- c("matrix1", "matrix2")
mean_p <- apply(percentage,2,mean)
mat <- c("matrix1", "matrix2")



percentage %>%
  as_data_frame() %>%
  gather(., Value , Percentage) %>%
  ggplot(., aes(x=Value,y=Percentage,color=rep(mat,ncol(percentage)))) +
  geom_bar(position = position_dodge(width = 0.8), stat = "identity", fill = "white")`

I tried to add

lab <- character()
for(i in 1:ncol(percentage)){
lab <- c(lab,"",sprintf('$\\oslash%s$',mean_p[i]))
}
geom_text(aes(label=lapply(lab,TeX)),vjust=0,show.legend = FALSE,color="lightblue")

but this doesn't convert the Latex Expression correctly. Has anybody an idea how to fix this Problem?

The output I want to generate should look like this:

enter image description here

Upvotes: 3

Views: 1666

Answers (1)

R&#233;mi Coulaud
R&#233;mi Coulaud

Reputation: 1714

I propose a solution using annotate wherease geom_text, it is largely inspired by the following solution :

Annotate a plot made with ggplot2 with an equation using latex2exp::TeX

lab <- character()
for(i in 1:ncol(percentage)){
  lab <- c(lab, paste('$\\oslash$', mean_p[i], '$\\%$', sep = " "))
  }

percentage %>%
  as_data_frame() %>%
  gather(., Value , Percentage) %>%
  ggplot(., aes(x=Value,y=Percentage,color=rep(mat,ncol(percentage)))) +
  geom_bar(position = position_dodge(width = 0.8), stat = "identity", fill = "white") + 
 annotate('text',  x = 1:6, y = percentage[2,], label = lapply(lab, function(x){TeX(x, output = "character")}), hjust=0, size = 4, parse = TRUE)

Upvotes: 2

Related Questions