Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add subscripts to ggplot2 axis.text

I want to use subscripts within each factor in a ggplot barplot.

d = structure(list(env = structure(c(1L, 3L, 4L, 2L, 5L, 7L, 6L), .Label = c("mean SS", 
"50% O2 @ 25 °C", "50% O2 @ 0 °C", "50% O2 @ 10 °C", "anoxic @ 0 °C", 
"anoxic @ 25 °C", "anoxic @ 10 °C"), class = "factor"), pco2_inc = c(60, 
138.652445968464, 144.328210839879, 112.560395996095, 173.615572249453, 
234.86228704132, 209.102964222973)), class = "data.frame", row.names = c(NA, 
-7L))

Given the data.frame above, I want to produce a plot like this:

ggplot(d, aes(env, pco2_inc)) + geom_col()

plot

How can I make the 2 in O2 subscripted for all the bar labels?

I've seen how the entire x axis label can be changed:

labs(x = expression(paste('50% ', O[2], ' @ 0 °C')))

but can't find how to get the axis.text to work.

like image 934
CephBirk Avatar asked May 25 '18 04:05

CephBirk


People also ask

How do you add subscripts in R?

Subscripts and Superscripts To indicate a subscript, use the underscore _ character. To indicate a superscript, use a single caret character ^ . Note: this can be confusing, because the R Markdown language delimits superscripts with two carets.

How do you make a superscript in R?

Superscript is “started” by the caret ^ character. Anything after ^ is superscript. The superscript continues until you use a * or ~ character. If you want more text as superscript, then enclose it in quotes.

Which arguments can be used to add labels in Ggplot?

To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code. Note: You can also use +labs(title = "Title") which is equivalent to ggtitle .


1 Answers

One option is to turn the env strings into valid plotmath expressions, so that they can be parsed properly. The code below takes care of that, though I'd be surprised if there isn't a more elegant approach.

library(tidyverse)

d = d %>%
  arrange(pco2_inc) %>% 
  mutate(env=gsub("O2", "O[2]", env),
         env=gsub(" ", "~", env),
         env=gsub("@", "'@'", env),
         env=gsub("%", "*'%'", env),
         env=gsub("~°", "*degree*", env))
                          env pco2_inc
1                     mean~SS  60.0000
2 50*'%'~O[2]~'@'~25*degree*C 112.5604
3  50*'%'~O[2]~'@'~0*degree*C 138.6524
4 50*'%'~O[2]~'@'~10*degree*C 144.3282
5       anoxic~'@'~0*degree*C 173.6156
6      anoxic~'@'~25*degree*C 209.1030
7      anoxic~'@'~10*degree*C 234.8623
ggplot(d, aes(reorder(env, pco2_inc), pco2_inc)) + geom_col() + 
  scale_x_discrete(labels=parse(text=unique(d$env))) +
  theme_classic(base_size=12) +
  theme(axis.text=element_text(colour="black", face="bold")) +
  labs(x="env")

enter image description here

like image 57
eipi10 Avatar answered Sep 23 '22 01:09

eipi10