在 ggplot2 中使用 `bquote(frac( .(number), .(number)) )` 绘制分数

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

我正在尝试使用

geom_tex(label = )
语法在
bquote(frac( .(number), .(number)) )
内绘制分数。

但 ggplot2 似乎无法识别这一点。有没有办法正确绘制这些分数?

可重复的数据和代码加上我尝试过的:

set.seed(0)
DATA <- data.frame(
  x=sample(0:1,50,T),
  y=sample(LETTERS[1:2],50,T))

library(ggplot2)

ggplot(DATA)+aes(x=x,y=after_stat(count)/ sapply(PANEL, \(x) sum(count[PANEL == x])))+
  geom_bar() +
  
# Problem starts with `label =`:
  geom_text(aes(y = after_stat(count)/ sapply(PANEL, \(x) sum(count[PANEL==x])),
            label = bquote(frac(.(after_stat(count)), .(sapply(PANEL, \(x) sum(count[PANEL==x])))))),
            vjust = -.1, color = "black", size = 2, stat = "count") +
  
  facet_grid(vars(y))
r ggplot2 plot tidyverse expression
1个回答
0
投票

一种选择是将绘图表达式创建为字符串,并在

parse=TRUE
中使用
geom_text
:

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.3.1

ggplot(DATA) +
  aes(x = x, y = after_stat(count) / sapply(PANEL, \(x) sum(count[PANEL == x]))) +
  geom_bar() +
  geom_text(
    aes(
      y = after_stat(count) / sapply(PANEL, \(x) sum(count[PANEL == x])),
      label = after_stat(
        paste0(
          "frac(", count, ", ",
          sapply(PANEL, \(x) sum(count[PANEL == x])), ")"
        )
      )
    ),
    vjust = -.1, color = "black", size = 2, stat = "count", 
    parse = TRUE
  ) +
  facet_grid(vars(y))

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