0

I have the next sample data

sample_data<-data.frame(nros=rnorm(20,mean=5,sd=2),group=rep(c("A","B","C","D"),5))

I want to add text in each plot, but this text should be dynamic. I mean I want for each histogram the mean of the variable nros in each group. I have tried this but I got the same mean for each plot.

sample_data|>ggplot(aes(x=nros))+geom_histogram()+
  geom_vline(aes(xintercept=mean(nros)),color="blue", linetype="dashed", size=1)+xlim(0,30)+
  geom_text(aes(x=mean(nros)+3,label=mean(nros),y=0.2))+facet_wrap(~group)

enter image description here

user3483060
  • 337
  • 2
  • 13

1 Answers1

0

I have set a seed for better comparability and then have made another DF me which contains the mean value for each group. In ggplot geom_line and geom_text are referring to this DF.

The label text was rounded a shifted a bit to the bottom.

library(tidyverse)

set.seed(123)
sample_data <- data.frame(nros = rnorm(20, mean = 5, sd = 2), group = rep(c("A", "B", "C", "D"), 5))

me <- sample_data |>
  group_by(group) |> 
  summarise(group_mean = mean(nros))

sample_data |>
  ggplot(aes(x = nros)) +
    geom_histogram() +
    geom_vline(data = me, aes(
      xintercept = group_mean), 
      color = "blue", linetype = "dashed", linewidth = 1) +
    xlim(0, 30) +
    geom_text(data = me, aes(
      x = group_mean, label = round(group_mean, 3), y = -0.05)) +
    facet_wrap(~group) +
      ylab("")

MarBlo
  • 4,195
  • 1
  • 13
  • 27