我正在绘制一个以化学式为分类以及与每个化学分类相关联的值的数据集:
data <- data.frame(compound = factor(c("SiO[2]", "Al[2]O[3]", "CaO")),
value = rnorm(3, mean = 1, sd = 0.25))
我想获得化学式中的下标以正确显示在轴标签中。我已经尝试过各种解决方案,涉及bquote()
,label_parsed()
,scales::parse_format()
和ggplot2:::parse_safe
(按照this thread),但是所有这些解决方案要么根本没有类别标签,要么使我一团糟。例如:
ggplot(data = data, aes(x = compound, y = value)) +
geom_col() +
scale_x_discrete(labels = scales::parse_format())
给出此错误消息:
Error in parse(text = x, srcfile = NULL) : 1:6: unexpected symbol
1: Al[2]O
^
有人可以帮忙吗?在使用x轴和x轴标签之前,我已经成功完成了此操作(通过labs()
,然后通过bquote()
或类似标签),针对该问题,我可以看到各种螺纹,但是似乎没有相同的解决方案用于类别标签。
更新:终于有了正确的parse()
例程,因此,如果化学品已经在数据框中正确格式化,则可以简单地解析它们以显示正确的标签。 (请注意,氧化铝需要使用波浪号(〜)字符)。
library(tidyverse)
library(rlang)
#>
#> Attaching package: 'rlang'
#> The following objects are masked from 'package:purrr':
#>
#> %@%, as_function, flatten, flatten_chr, flatten_dbl, flatten_int,
#> flatten_lgl, flatten_raw, invoke, list_along, modify, prepend,
#> splice
compounds = c("SiO[2]", "Al[2]~O[3]", "CaO[1]")
data <- tibble(compound = compounds,
value = rnorm(3, mean = 1, sd = 0.25))
data %>%
ggplot(aes(x = compound, y = value)) +
geom_col() +
scale_x_discrete(labels = rlang::parse_exprs)
由reprex package(v0.3.0)在2019-11-21创建
以前的更新:用转换表来稍微扩展一些代码,以获取bquote()
表达式。相同的基本思想,但现在不仅可以硬性地粘贴在标签中,因此应与过滤器,构面等一起使用。
library(tidyverse)
compounds = c("SiO[2]", "Al[2]O[3]", "CaO[1]")
translation = c("SiO[2]" = bquote(SiO[2]),
"Al[2]O[3]" = bquote(Al[2] ~ O[3]),
"CaO[1]" = bquote(CaO))
data <- tibble(compound = compounds,
value = rnorm(3, mean = 1, sd = 0.25))
ggplot(data = data, aes(x = compound, y = value)) +
geom_col() +
scale_x_discrete(labels = translation)