0

Does anyone know how I can plot factor levels containing text with superscripts? In the example below I would like to have A^1 and B^3 in the x-axis as superscript text (without '^')

# Fake dataframe
size <- 20

df <- data.frame(grp = sample(c("A^1", "B^3", "C"), size = size, replace = TRUE),
                 value = rnorm(size, mean = 10, sd = 1)) %>%
  mutate(grp = as.factor(grp)) %>%
  group_by(grp) %>%
  summarise(mean = mean(value, na.rm=TRUE)) %>%
  ungroup()

# barplot
df %>%
  ggplot(aes(x = grp, y = mean)) +
    geom_col()

zx8754
  • 52,746
  • 12
  • 114
  • 209
D. Studer
  • 1,711
  • 1
  • 16
  • 35

2 Answers2

3

We can use ggtext::element_markdown

# install.packages('ggtext')

df %>%
  ggplot(aes(x = grp, y = mean)) +
  geom_col() +
  theme(axis.text.x = ggtext::element_markdown())

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
1

You can use expression and specify manually your labels:

xlabels <- c("A^1" = expression("A"^1), "B^3" = expression("B"^3), "C" = "C")

# barplot
df %>%
  ggplot(aes(x = grp, y = mean)) +
  geom_col() +
  scale_x_discrete(labels = xlabels)

enter image description here

Check out this link: https://statisticsglobe.com/add-subscript-and-superscript-to-plot-in-r

Edo
  • 7,567
  • 2
  • 9
  • 19