Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 - superscript in x axis ticks text

Tags:

r

ggplot2

I'm trying to get the text of two variables on the x axis to have superscript. I want the '+' to be superscript but it just ends up displaying the whole code no matter what I try. I've tried making separate labels for it and also tried to keep it more simple

test.labs=as_labeller(c('CD4Gated' = 'CD4^+ cells', 'CD8Gated' = 'CD8^+ cells', 'Bcell' 
= "B cells"), default = label_parsed)

bFICOLL + scale_x_discrete(labels=c(CD4Gated = "CD4^+ cells", CD8Gated = "CD8^+ cells", 
Bcell = "B cells"))

In another graph (after lots of searching!) I managed to get the title to include superscript with the code below but it doesn't work with tick labels.

ggtitle('Spring FEC &' ~~ CD4^'+' ~~ 'cells')

This is the code for the graph. Hopefully somebody is able to tell me what I'm doing wrong?

  bFICOLL <-  ggplot(LymphOrder, aes(x=WBC, y=Percentage, fill=Diagnosis, 
  shape=Diagnosis)) + 
  geom_violin() +
  facet_wrap(~Season, scale="free")+
  theme(strip.text.x = element_text(size = 30))+
  geom_point(pch = 21, position = position_jitterdodge())+
  scale_fill_manual(values=c("#56B4E9", "#009E73"))+ 
  scale_shape_manual(values=c(1,2))+
  theme(panel.background = element_blank(), axis.line = element_line(colour = "black"))+
  theme(strip.background = element_rect( color="black", fill="#FFFFFF", size=1.5, 
  linetype="solid"))+
  ggtitle('Lymphocyte subsets')+
  theme(plot.title = element_text(size = 40, face = "bold")) +
  ylab('Percentage') +
  xlab("Lymphocytes")+
  ylim(0,80)+
  theme(axis.ticks.length = unit(5, "pt"))+
  theme(axis.title.x = element_text(size=20))+
  theme(axis.text.x = element_text(size=15))+
  theme(axis.text.x = element_text(angle = 30, hjust = 1))+
  theme(axis.text.y = element_text(size=20))+
  theme(axis.title.y = element_text(size=20))+
  theme(legend.title = element_blank(),
    legend.text = element_text(size = 20))
  bFICOLL + scale_x_discrete(labels=c(CD4Gated = "CD4^+ cells", CD8Gated = "CD8^+ 
  cells", 
  Bcell = "B cells"))

Boxplot without superscript in x axis tick labels

like image 412
Len Avatar asked Jul 08 '26 13:07

Len


1 Answers

Using the ggtext package:

library(ggplot2)
library(ggtext)

my_labs <- c(setosa = "CD4^+ cells", versicolor = "CD8^+ 
  cells", virginica = "B cells")

ggplot(iris, aes(Species, Sepal.Length)) + 
  geom_boxplot() +
  scale_x_discrete(labels = my_labs) +
  theme(axis.text.x = element_markdown())

Created on 2022-06-14 by the reprex package (v2.0.1)

like image 112
tjebo Avatar answered Jul 10 '26 02:07

tjebo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!