Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotation above bars:

Tags:

r

ggplot2

dodged bar plot in ggplot again has me stumped. I asked about annotating text above bars on here a few weeks back (LINK) and got a terrific response to use + stat_bin(geom="text", aes(label=..count.., vjust=-1)). I figured since I already have the counts I'll just supply them with out the .. before and after and I told stat_bin that the position was dodge. It lines them up over the center of the group and adjusts up and down. Probably something minor. Please help me to get the text over the bars.

enter image description here

mtcars2 <- data.frame(type=factor(mtcars$cyl), 
    group=factor(mtcars$gear))
library(plyr); library(ggplot)
dat <- rbind(ddply(mtcars2,.(type,group), summarise,
    count = length(group)),c(8,4,NA))

p2 <- ggplot(dat,aes(x = type,y = count,fill = group)) + 
    geom_bar(colour = "black",position = "dodge",stat = "identity") +
    stat_bin(geom="text", aes(position='dodge', label=count, vjust=-.6)) 
like image 856
Tyler Rinker Avatar asked Apr 26 '12 04:04

Tyler Rinker


People also ask

How to add annotation on top of bars in barplot with Python?

With the argument xytext, we have annotation on top of the bars. How To Add Labels on top of Bars in Barplot with Python? We can customize annotation a bit. Sometimes adding annotation over the bar can overlap with the plot outline. A solution is to add the annotation inside the bars of barplot.

How to annotate each bar in Seaborn barplot?

In the code below, we loop through each bar in the Seaborn barplot object and use annotate () function to get the height of the bar, decide the location to annotate using barwidth, height and its coordinates. We can also control the size the text on top of each bar.

How do you annotate a bar in matlpotlib?

Adding the annotations. Our strategy here will be to iterate all over the bars and put a text over all of them that will point out the values of that particular bar. Here we will use the Matlpotlib’s function called annotate ().

What does the height of the bars represent in the barplot?

Here, the height of the bars represent numerical values in the data. We can labels to bars in barplot using ggplot2’s function geom_text ().


1 Answers

I was having trouble getting the position dodges to line up, so I ended up creating a position_dodge object (is that the right terminology?), saving it to a variable, and then using that as the position for both geoms. Somewhat infuriatingly, they still seem to be a little off centre.

dodgewidth <- position_dodge(width=0.9)
ggplot(dat,aes(x = type,y = count, fill = group)) + 
  geom_bar(colour = "black", position = dodgewidth ,stat = "identity") +
  stat_bin(geom="text", position= dodgewidth, aes(x=type, label=count), vjust=-1)

enter image description here

like image 73
Marius Avatar answered Oct 08 '22 20:10

Marius