r - 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()
或类似)成功地完成了此操作,并且我可以看到针对该问题的各种线程,但相同的解决方案似乎不适用于类别标签。
解决方案
更新:终于找到了正确的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)
推荐阅读
- kubernetes - GKE Ingress 无法在一台主机下路由多条路径
- npm-install - 在 Linux 上安装 create react app 时超出最大调用堆栈大小
- python - 如何在 Python 上使用 Selenium 分享帖子?
- javascript - redis hmget node.js async/await 不工作
- python-3.x - 如何从 site-packages 目录手动导入 python 模块?
- c# - WPF DataGrid 禁用自动滚动
- firebase - Firestore 按到期日查询今天到期的项目
- c# - 如何在控制台中打印二维字符数组矩阵?
- bash - 如何在 Mac 终端上正确设置 bash 配置文件
- java - 如何使 TextField 填充包含多个节点的窗格的所有剩余宽度?