Madison Heard
Madison Heard

Reputation: 23

How to add subscripts to labels on boxplot using ggplot 2

I am having trouble adding subscripts my categories on the x axis. My code reads:

xlab("Treatment Combination") +
ylab("CS Activity (IU/gfw)") +
scale_x_discrete(labels = c("Control/Control" = "MControl à LControl",
                            "Hypoxic/Hypoxic" = "MHypoxia à LHypoxia"))+

I am trying to change "MControl à LControl" into "M" as a subscript before a regular "Control" and again for "L" as a subscript before a regular "Control".

This image shows the category labels without subscripted "M" and "L":

This image shows the category labels without subscripted "M" and "L"

Any ideas on how to makes these subscripted?

Thanks in advance for your help!

Upvotes: 1

Views: 530

Answers (1)

atsyplenkov
atsyplenkov

Reputation: 1304

You can do something like this with expression function. Be aware, that expression wouldn't be parsed if you write expression([M]*"Control à LControl"). You always need something to add before subscript brackets. In your case a code chunk should be expression(""[M]*"Control à "[L]*"Control"). See example below:

library(ggplot2)

# Base example
iris %>% 
  as_tibble() %>% 
  ggplot(aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  # Here comes the magic!
  scale_x_discrete(name = "",
                   # Note that we put an empty space before the subscript
                   labels = c(expression(""[M]*"Setosa"),
                              expression(""[L]*"Versicolor"),
                              expression(""[Q]*"Virginica")))

enter image description here

Upvotes: 1

Related Questions