Alignment of numbers on the individual bars with ggplot2

前端 未结 1 566
北恋
北恋 2020-12-09 23:05

I want to show numbers on the individuals bars in the following graph.

df <- structure(list(A = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L,
3L), .Label =         


        
相关标签:
1条回答
  • 2020-12-09 23:16

    You need to add position=position_dodge(width=0.9) to the geom_text call.

    Cleaning up your code a little gives:

    p <- ggplot(data=df, aes(x=A, y=Freq))+
        geom_bar(aes(fill=B), position = position_dodge()) + 
        geom_text(aes(label = paste(sprintf("%.1f", Freq*100), "%", sep=""),
                      y = Freq+0.015, x=A),
                  size = 3, position = position_dodge(width=0.9)) +
        scale_y_continuous(formatter = "percent") +
        theme_bw()
    

    which results in

    enter image description here

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