如何将下标添加到ggplot2 axis.text [英] How to add subscripts to ggplot2 axis.text
问题描述
我想在ggplot条形图中的每个因子中使用下标.
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))
鉴于上面的data.frame,我想生成一个像这样的图:
Given the data.frame above, I want to produce a plot like this:
ggplot(d, aes(env, pco2_inc)) + geom_col()
如何为所有条形标签的O2
中的2
下标?
How can I make the 2
in O2
subscripted for all the bar labels?
我已经知道如何更改整个x轴标签:
I've seen how the entire x axis label can be changed:
labs(x = expression(paste('50% ', O[2], ' @ 0 °C')))
,但找不到如何使axis.text
正常工作.
but can't find how to get the axis.text
to work.
推荐答案
一种选择是将env
字符串转换为有效的plotmath
表达式,以便可以对其进行正确解析.下面的代码可以解决这个问题,但是如果没有更优雅的方法,我会感到惊讶.
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")
这篇关于如何将下标添加到ggplot2 axis.text的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!