Home > OS >  Why would stat_summary not add up the labels on my barplot?
Why would stat_summary not add up the labels on my barplot?

Time:04-08

I have an aggregated dataset which looks like this one:

place<-c('PHF','Mobile clinic','pharmacy','PHF','pharmacy','PHF','normal shop','pharmacy')
District<-c('District1','District1','District1','District2','District2','District3','District3','District3')
cat<-c('public','public','private','public','private','public','private','private')
Freq<-c(7,2,5,4,7,5,1,8)
Q14_HH<-data.frame(place,District,cat,Freq)

I create a barplot which looks great:

plot<- ggplot(data = Q14_HH, aes(x=place,y=Freq,fill=cat))  
  geom_bar(stat='identity')  
  labs(title="Where do you get your medicines from normally? (human)", 
       subtitle='Precentage of households, n=30',x="", y="Percentage",fill='Outlet type')  
  theme(axis.text.x = element_text(angle = 90, hjust=1,vjust=0.5))

Now I want to put the sum of the frequencies on top of each bar i.e. for each place variable:

plot  stat_summary(geom='text',aes(label = Freq,group=place),fun=sum)

But for some reason it won't calculate the sum. I get a warning message: Removed 2 rows containing missing values (geom_text)enter image description here

Can someone help me understand what is happening here?

CodePudding user response:

As you are computing the sum you have to map the computed y value on the label aes using label=..y.. or label=after_stat(y):

library(ggplot2)

plot <- ggplot(data = Q14_HH, aes(x = place, y = Freq, fill = cat))  
  geom_bar(stat = "identity")  
  labs(
    title = "Where do you get your medicines from normally? (human)",
    subtitle = "Precentage of households, n=30", x = "", y = "Percentage", fill = "Outlet type"
  )  
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))

plot   stat_summary(geom = "text", aes(label = ..y.., group = place), fun = sum)

  • Related