问题
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()
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.
回答1:
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")
来源:https://stackoverflow.com/questions/50521699/how-to-add-subscripts-to-ggplot2-axis-text