添加带有 x 条和舍入值的 geom_text

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

我有一个 6 面 ggplot2 条形图。我希望每个方面都用其各自的平均值进行注释。像这样:

x̄ = 0.25

所以我一直在努力:

geom_text (data = averages, inherit.aes = FALSE,
           aes (label = expression (bar (x) == round (Mean, 2)), x = 30, y = 61.5)) +

但我总是得到这样的回报:

Don't know how to automatically pick scale for object of type <expression>. Defaulting to continuous.
Error in `geom_text()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 2nd layer.
Caused by error in `compute_aesthetics()`:
! Aesthetics are not valid data columns.
✖ The following aesthetics are invalid:
✖ `label = expression(bar(x) == round(Mean, 2))`
ℹ Did you mistype the name of a data column or forget to add `after_stat()`?
Run `rlang::last_trace()` to see where the error occurred.

我还尝试了这两篇文章中的大多数建议:在绘图标签中组合粘贴()和表达式()函数将数学符号和下标与常规字母混合

有什么办法可以做到这一点吗?

r ggplot2 expression geom-text
2个回答
1
投票

一种选择是将

paste(0)
parse=TRUE
一起使用,如下所示:

averages <- data.frame(
  facet = letters[1:6],
  Mean = 1:6
)

library(ggplot2)

ggplot() +
  geom_text(
    data = averages, inherit.aes = FALSE,
    aes(label = paste0("bar(x) == ", round(Mean, 2)), x = 30, y = 61.5),
    parse = TRUE
  ) +
  facet_wrap(~facet)


0
投票

您可以使用

bquote
代替
expression
,并确保转义
.()
内的任何计算。注释最好使用
annotate
而不是
geom_text

添加
library(ggplot2)

Mean <- mean(iris$Sepal.Length)

ggplot(iris) +
  geom_point(aes(Sepal.Width, Sepal.Length, color = Species)) +
  annotate('text', x = 3.25, y = 8,
           label = bquote(bar (x) == .(round(Mean, 2))))

enter image description here

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