Parse superscript in discrete axis values on geom_bar
Asked Answered
H

1

1

I'm trying to add a superscript to some x-axis values in order to connect to a footnote that'll be at the bottom of the page. The easy workaround would just be an asterisk instead of ^a but that won't work for my purposes.

I did a lot of searching and while there's plenty of posts about superscripts in axis labels, I couldn't find any about superscripts in axis values. Most of them appeared to centera round adding a gg + labs(x = expression("blah^a")).

I did find this post about parsing superscripts inside a geom_text() but it appears the same doesn't work for a geom_bar().

Here's some test data:

library(ggplot2)

dat <- data.frame(x = c("alpha", "bravo^a"),
                  y = c(10, 8))

ggplot(data = dat) +
  geom_bar(aes(x = x, 
               y = y),
           stat = "identity")
Hexane answered 27/8, 2018 at 12:46 Comment(0)
B
4

You just need to parse the text inside scale_x_discrete

Edit: add geom_text example

library(ggplot2)

dat <- data.frame(x = c("alpha", "bravo^a"),
                  y = c(10, 8))

### need to convert x to factor if R >= 4.0
dat$x <- factor(dat$x)

ggplot(data = dat) +
  geom_bar(aes(x = x, 
               y = y),
           stat = "identity") +
  scale_x_discrete(labels = parse(text = levels(dat$x))) +
  geom_text(aes(x = x, y = y,
                label = x), 
            parse = TRUE, 
            nudge_y = 1,
            size = 5) +
  theme_minimal(base_size = 14)

Created on 2018-08-27 by the reprex package (v0.2.0.9000).

Berey answered 27/8, 2018 at 13:11 Comment(1)
On R version >= 4, you need to convert dat$x to a factor for this to workMeganmeganthropus

© 2022 - 2024 — McMap. All rights reserved.