使用 'bquote(frac( .(数字)、.(数字)))' 在 ggplot2 中

Plotting fractions using `bquote(frac( .(number), .(number)) )` in ggplot2

提问人:Simon Harmel 提问时间:10/30/2023 最后编辑:Simon Harmel 更新时间:10/31/2023 访问量:23

问:

我正在尝试使用语法在内部绘制分数。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 绘制 整洁的表达式

评论


答:

0赞 stefan 10/31/2023 #1

一种选择是将 plotmath 表达式创建为字符串,并在 :parse=TRUEgeom_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))

评论

0赞 Simon Harmel 10/31/2023
谢谢!虽然我希望有一种方法可以让分子和分母更接近派系线。现在,它们离分数线太远了,如果柱线接近 60%,分子就不会显示。
1赞 stefan 10/31/2023
是的。如果面板尺寸可以调整以适应这种情况,那就太好了。但当然可以增加规模的扩展,例如尝试为标签腾出空间。scale_y_continuous(expand = expansion(add = c(0, .1))
0赞 Simon Harmel 10/31/2023
只是好奇,我们真的可以从整个 ggplot 对象中使用 ggplot 吗?count