Jago
Jago

Reputation: 23

Adding superscript to axis tick labels that contain / and ; for a ggplot2 object

I'm trying to create axis tick labels for addition to a ggplot2 object using scale_x_discrete(labels = ). I've tried using bquote and the expression function for superscripts however I keep getting error messages saying unexpected symbol when I add / and ; signs into the string. Does anyone know a way around this? I've attached an example of one of the tick labels I want to include. If you need any more information please let me know, thanks.

enter image description here

Upvotes: 0

Views: 400

Answers (2)

Peter
Peter

Reputation: 12739

Here's a way using scale_x_discrete and expression with plotmath.

library(ggplot2)


ggplot(ToothGrowth, aes(supp, len)) +
  geom_bar(stat = "sum", show.legend = FALSE)+
  scale_x_discrete(breaks = c("OJ", "VC"),
                   labels = c(expression(Cul3^"+/+"*";Ctrl"), "Some other label"))+
  theme(axis.text.x = element_text(size = 18))

Created on 2022-10-04 with reprex v2.0.2

Upvotes: 0

Jon Spring
Jon Spring

Reputation: 66945

This should be possible with ggtext if you formulate your formatting with markdown:

library(ggplot2); library(ggtext)
mtcars2 <- mtcars
mtcars2$x = ifelse(mtcars2$gear == 5, "Cul3<sup>+/+</sup>;Ctrl", mtcars2$gear)
ggplot(mtcars2, aes(x, mpg)) +
  geom_point() +
  theme(axis.text.x = element_markdown(size = 18))

enter image description here

Upvotes: 1

Related Questions