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'))