Search code examples
rggplot2labelgeom-bar

ggplot2 - add subscript after label in bar


I am trying to add a label (noun) after another label (number) in a bar chart (example below). It works well with normal text (creating a column like Value2 in the example), but if I need a subscript, It doesn't work.

I tried some workarounds with "bquote" and "expression" but didn't figure it out. The idea is to have the numbers in the GHG variable appearing as a subscript in the Figure (CO[2], CH[4] and N[2]O).

Any insights? Simple working example below

GHG = c("CH4", "CO2", "N2O")

Value = c(10, 5, 2)

Value2 = c("10 - CH4", "5 - CO2", "2 - N2O")

df = data.frame(GHG, Value, Value2)

g1 = ggplot(data=df, aes(x=GHG, y=Value)) +
  
  geom_bar(stat="identity") +
  
  geom_text(data=df, aes(label = Value2, y= Value, hjust=-0.1), size=4) +
        
  xlab ("") +
  ylab ("") +
  
  coord_flip() +
  
  scale_y_continuous(limits=c(0,11)) + 
  
  theme(text=element_text(family="serif", size=15, colour="black")) +
  theme(axis.text.x=element_text(size=15, colour = "black")) +
  
  easy_remove_y_axis() 

g1

enter image description here


Solution

  • One way would be to use ggtext package where you can use <sub> and <sup> tags.

    library(ggplot2)
    library(ggtext)
    library(ggeasy)
    
    GHG = c("CH4", "CO2", "N2O")
    Value = c(10, 5, 2)
    Value2 = c("10 - CH<sub>4</sub>", "5 - CO<sub>2</sub>", "2 - N<sub>2</sub>O")
    df = data.frame(GHG, Value, Value2)
    
    ggplot(data=df, aes(x=GHG, y=Value)) +
      geom_col() +
      geom_richtext(aes(label = Value2, hjust=-0.1), size=4) +
      xlab ("") +
      ylab ("") +
      coord_flip() +
      scale_y_continuous(limits=c(0,11)) + 
      theme(text=element_text(family="serif", size=15, colour="black")) +
      theme(axis.text.x=element_text(size=15, colour = "black")) + 
      easy_remove_y_axis() 
    

    enter image description here