George
George

Reputation: 1463

Ho to add the count values calculated in the geom_histogram on top of the bars in R

I'd like to add the count values calculated in the geom_histogram function on ggplot2. I've put the ggplot2 into a loop so I can produce multiple plots, in my case 30 but for ease, here is a dummy set for only four plots. Facet wrap didn't work as the geom density was pooling the data across all factors before calculating proportions, rather than within a factor/variable. To produce this plot, I've essentially mixed a whole bunch of code from various sources so credit to them.

              library(dplyr)
              library(ggplot2)
              library(ggridges)
              library(reshape2)
              library(gridExtra)
       #Make the data#       
        df.fact <- data.frame("A"=rnorm(400, mean = 350, sd=160),"B"=rnorm(400, mean = 300, sd=100), "C"=rnorm(400, mean = 200, sd=80), names=rep(factor(LETTERS[23:26]), 100))
        df.test<-melt(df.fact, id.vars = "names", value.name = "Length2")
        names(df.test)[names(df.test) =="variable"] <- "TSM.FACT"

    #Create the plotlist##      
        myplots <- list()

    #Loop for plots##
        for(i in 1:(length(unique(df.test$names)))){ 
          p1 <- eval(substitute(
            ggplot(data=df.test[df.test$names == levels(df.test$names)[i],], aes(x=Length2, group=TSM.FACT, colour = TSM.FACT, fill=TSM.FACT)) +
              geom_histogram(aes( y = stat(width*density)), position = "dodge", binwidth = 50, alpha =0.4, show.legend=T)+
              ggtitle(paste0(levels(df.test$names)[i]))+
              geom_density_line(stat="density", aes(y=(..count..)/sum(..count..)*50), alpha=0.3, size=0.5, show.legend=F) +
              geom_vline(data=ddply(df.test[df.test$names == levels(df.test$names)[i],], ~ TSM.FACT,  numcolwise(mean)), mapping=aes(xintercept = Length2, group=TSM.FACT, colour=TSM.FACT),  linetype=2, size=1, show.legend=F) +
              scale_y_continuous(labels = percent_format()) +
              ylab("relative frequency") +
              scale_color_manual(values= c("#00B2EE",  "#1E90FF",  "#104E8B")) +
              scale_fill_manual(values= c("#00B2EE",  "#1E90FF", "#104E8B")) +
            theme_bw() + theme(
              plot.title = element_text(lineheight=0.5, hjust= 0.5, size=10),
              strip.text.y = element_text(hjust = 1, angle = 0),
              strip.text.x = element_text(size=10, vjust = 0.9), 
              strip.text=element_text(margin = margin(t=0.3,r=1,b=0.3,l=1), size=8, debug = F, vjust=0.2),
              strip.background = element_blank(),
              axis.text.x = element_text(size=8, angle=0, vjust=0.2, margin = margin(t=0.3,r=0.1,b=0.3,l=0.1)),
              axis.title.x=element_blank(),
              axis.title.y=element_blank(),
              axis.line.x=element_line(colour="black"),
              axis.line.y=element_line(colour="black"),
              panel.grid.minor = element_blank(), 
              panel.border=element_blank(),
              panel.background=element_blank(),  
              legend.position=(c(0.9,0.9)),
              legend.title = element_blank(), 
              legend.key = element_blank()),
            list(i = i)))
          print(i)
          print(p1)
          myplots[[i]] <- p1 
          plot(p1)
        }

#Join the plots
panelplot=grid.arrange(plotlist = myplots, grobs = myplots, shared.legend=T)

enter image description here

Upvotes: 1

Views: 879

Answers (1)

LukeXywalker
LukeXywalker

Reputation: 66

Unfortunately I am unable to reproduce your example. I can recommend adding a column that includes the sum of each bar (let's name it "Bar")

The required addition to the ggplot code then involves:

geom_text(aes(label = Bar), position = position_stack(vjust = 1)) +

The text height above the bar can be adjusted with vjust

Upvotes: 2

Related Questions