如何使`bquote`用符号替换存储在变量中的希腊字母?

问题描述 投票:0回答:2

我想在图上动态标记轴。标签来自数据框,包含希腊字母以及超级/预订。

在静态情况下,如果我会知道标签字母,bquote会很好。但是,如果标签字符串来自变量,则bquote失败。

这演示了我想要实现的目标:

a <- "alpha"
b <- "beta"
ggplot(data.frame(x=c(1), y=c(1)), aes(x, y)) + 
  geom_point() +
  labs(x = bquote(.(a)[.(b)])) + ## will output the greek letters by "name"
  labs(y = bquote(alpha[beta]))  ## the greek letter-names are replaces by the symbols

bqu

r ggplot2 label
2个回答
0
投票

如果数据在数据框中,如下所示,则可以这样做

df <- data.frame(a, b, stringsAsFactors = FALSE)
library(ggplot2)

ggplot(data.frame(x=c(1), y=c(1)), aes(x, y)) + 
   geom_point() +
   labs(x = with(df, bquote(.(a)[.(b)]))) +
   labs(y = with(df, bquote(alpha[beta])))

enter image description here


0
投票

使用rlang::sym将a和b变量转换为符号。

library("tidyverse")

a <- "alpha"
b <- "beta"

ggplot(data.frame(x = c(1), y = c(1)), aes(x, y)) +
  geom_point() +
  labs(x = bquote(.(sym(a))[.(sym(b))])) +
  labs(y = bquote(alpha[beta]))

“”

reprex package(v0.3.0)在2019-11-04创建

© www.soinside.com 2019 - 2024. All rights reserved.