1

I need change the labels with custom labels that are not in the data because I want to introduce some latex formulas in the labels.

To illustrate the issue I will use an example I copied from https://www.r-graph-gallery.com/48-grouped-barplot-with-ggplot2.

# library
library(ggplot2)
library(latex2exp)

# create a dataset
specie <- c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )
condition <- rep(c("normal" , "stress" , "Nitrogen") , 4)
value <- abs(rnorm(12 , 0 , 15))
data <- data.frame(specie,condition,value)
 
# Grouped
ggplot(data, aes(fill=condition, y=value, x=specie)) + 
    geom_bar(position="dodge", stat="identity")

This example produces the following plot:

enter image description here

Instead of the labels Nitrogen, normal, and stress, I want to use latex formulas as TeX('$\\alpha^2$'), TeX('$\\beta^3$') and TeX('$\\alpha+\\beta$'). Of course, I prefer to modify the plot, but not the data. How can I do it?

Daniel Hernández
  • 1,279
  • 8
  • 15
  • 1
    Did you try any of these solution? https://stackoverflow.com/questions/44310088/how-to-add-latex-code-in-ggplot2-legend-labels – Ronak Shah Oct 17 '20 at 15:30

1 Answers1

1

Try this using expression() where you can wrap all your labels and then use scale_fill_manual() or scale_fill_discrete():

# library
library(ggplot2)
# create a dataset
specie <- c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )
condition <- rep(c("normal" , "stress" , "Nitrogen") , 4)
value <- abs(rnorm(12 , 0 , 15))
data <- data.frame(specie,condition,value)
#Labs
labs <- expression(alpha^2,beta^3,alpha+beta)
# Grouped
ggplot(data, aes(fill=condition, y=value, x=specie)) + 
  geom_bar(position="dodge", stat="identity")+
  scale_fill_manual(labels=labs,values=c('tomato','cyan3','palegreen'))

Output:

enter image description here

Or this option for elegant spacing:

#Labs
labs <- expression(alpha^2,beta^3,~~~alpha+beta)
# Grouped
ggplot(data, aes(fill=condition, y=value, x=specie)) + 
  geom_bar(position="dodge", stat="identity")+
  scale_fill_manual(labels=labs,values=c('tomato','cyan3','palegreen'))

Output:

enter image description here

Using scale_fill_discrete():

# Grouped
ggplot(data, aes(fill=condition, y=value, x=specie)) + 
  geom_bar(position="dodge", stat="identity")+
  scale_fill_discrete(labels=labs)

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84