Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading