Search code examples
rggplot2facet-wrap

How do I adjust the text in each panel?


I'm trying to add text to each plot with the mean values of each distribution. The problem is I don't how to adjust the text so that they don't lie on top of each other. I would also like to add something like "Male Mean = xxx" and "Female mean= xxx". Sample data is:

     cost gender year
1 305.665 Female 2013
2 194.380 Female 2013
3 462.490 Female 2013
4 200.430 Female 2013
5 188.570 Female 2013
6 277.245 Female 2013

The code is:

library(dplyr)
library(ggplot2)
costs<-read.table("cost_gender_1.txt",header=TRUE)
df<-data.frame(costs)
meanData = df %>% group_by(gender, year) %>% summarise(meancost = mean(cost))
ggplot(df, aes(cost,fill=gender)) +
  geom_histogram(breaks=seq(0,3000,by=30), position = "dodge") +
  facet_wrap(~year) +
  labs(x="Costs",y="Number of Members")+ggtitle("All Tiers") +
  geom_text(data=meanData, aes(label=round(meancost,1), x=2500, y=2300), colour="#F8766D", hjust=1) +
  theme(plot.title = element_text(color="black", size=14, face="bold"))

The meancosts are:

   gender  year meancost
   <chr>  <int>    <dbl>
 1 Female  2013     506.
 2 Female  2014     502.
 3 Female  2015     471.
 4 Female  2016     526.
 5 Female  2017     507.
 6 Female  2018     530.
 7 Male    2013     492.
 8 Male    2014     481.
 9 Male    2015     449.
10 Male    2016     492.
11 Male    2017     469.
12 Male    2018     488.

and the output looks like this:

enter image description here


Solution

  • One solution would be to use e.g. position = "stack". Otherwise, just use separate y-values....

    y = rep(c(2300, 2200), each = n_distinct(meanData$year))