I have a 6-facet ggplot2 bar chart. I want each facet to be annotated with its respective mean value. Like this:
x̄ = 0.25
So I have been trying:
geom_text (data = averages, inherit.aes = FALSE,
aes (label = expression (bar (x) == round (Mean, 2)), x = 30, y = 61.5)) +
But I always get this in return:
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.
I've also tried most suggestions from these two posts: Combining paste() and expression() functions in plot labels and Putting mathematical symbols and subscripts mixed with regular letters
Is there any way to do this?
One option would be to use paste(0)
with parse=TRUE
like so:
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)