在ggplot轴类别标签中正确显示化学式

时间:2019-11-21 21:07:38

标签: r parsing ggplot2 subscript chemistry

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

JWTAuthenticationFilter customFilter = new JWTAuthenticationFilter(authenticationManager());
customFilter.setFilterProcessesUrl("/api/login");

http.addFilter(customFilter);

我想让化学式中的下标正确显示在轴标签中。我尝试了各种解决方案,涉及JWTAuthenticationFilter/api/logindata <- data.frame(compound = factor(c("SiO[2]", "Al[2]O[3]", "CaO")), value = rnorm(3, mean = 1, sd = 0.25)) bquote()(根据this thread),但所有这些都给我没有类别标签完全是一团糟。例如:

label_parsed()

给出此错误消息:

scales::parse_format()

有人可以帮忙吗?在使用x轴和x轴标签之前,我已经成功完成了此操作(通过ggplot2:::parse_safe,然后通过ggplot(data = data, aes(x = compound, y = value)) + geom_col() + scale_x_discrete(labels = scales::parse_format()) 或类似标签),针对该问题,我可以看到各种线程,但是解决方案相同似乎不适用于类别标签。

1 个答案:

答案 0 :(得分:1)

已更新:最后得到了正确的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)