Annotation above bars:

后端 未结 2 675
长发绾君心
长发绾君心 2020-12-01 18:42

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

相关标签:
2条回答
  • 2020-12-01 19:27

    Updated geom_bar() needs stat = "identity"

    I think this does what you want as well.

    mtcars2 <- data.frame(type = factor(mtcars$cyl), group = factor(mtcars$gear))
    library(plyr); library(ggplot2)
    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(stat = "identity", colour = "black",position = "dodge", width = 0.8) +
      ylim(0, 14) +
      geom_text(aes(label = count, x = type, y = count), position = position_dodge(width = 0.8), vjust = -0.6)
    p2
    

    enter image description here

    0 讨论(0)
  • 2020-12-01 19:35

    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

    0 讨论(0)
提交回复
热议问题