首页 > 解决方案 > ggplot 轴类别标签中化学式的正确显示

问题描述

我正在绘制一个以化学公式为类别的数据集,以及与每个类别相关的值:

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

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()或类似)成功地完成了此操作,并且我可以看到针对该问题的各种线程,但相同的解决方案似乎不适用于类别标签。

标签: rparsingggplot2subscriptchemistry

解决方案


更新:终于找到了正确的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 包(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)

推荐阅读