0

Context

I am ploting a barplot using ggplot2, and I want to use subscript and supscript in x-axis text.

I found that I could use scale_x_discrete(labels=parse(text=unique(...))) to do this when my x-xis is a character vector from that answer.

But in my situation, my x-axis is not a character vector but a factor vector. The solution does not work for me.

Question

how to use subscript and supscript in axis text in R when the text is a factor?

Reproducible code

df1 = data.frame(x = c("NH[4]^'+'", "SO[4]^'2-'"),
                 y = 1:2)

df2 = df1 %>% mutate(x = factor(x))

# when x is character vector I can use subscript and supscript well
df1 %>% 
  ggplot(aes(x = x, y = y)) +
  geom_col() +
  scale_x_discrete(label = parse(text = df1$x)) +
  theme(axis.text.x = element_text(color = 'red'))

# when x is factor vector I cannot parse it
df2 %>% 
  ggplot(aes(x = x, y = y)) +
  geom_col() +
  scale_x_discrete(label = parse(text = df2$x))+
  theme(axis.text.x = element_text(color = 'red'))

enter image description here enter image description here

zhiwei li
  • 1,635
  • 8
  • 26

1 Answers1

0

Actually, df2$x gives you the level of the factor rather than the character value itself. To get the values instead, you need to read it as a character, as follows:

df2 %>% 
  ggplot(aes(x = x, y = y)) +
  geom_col() +
  scale_x_discrete(label = parse(text = as.character(df2$x)))+
  theme(axis.text.x = element_text(color = 'red'))

Hope it helps.

Taher A. Ghaleb
  • 5,120
  • 5
  • 31
  • 44