Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alignment of numbers on the individual bars with ggplot2

Tags:

r

ggplot2

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 = c("0-50,000", "50,001-250,000", "250,001-Over"), class = "factor"),
    B = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("0-50,000",
    "50,001-250,000", "250,001-Over"), class = "factor"), Freq = c(0.507713884992987,
    0.258064516129032, 0.23422159887798, 0.168539325842697, 0.525280898876405,
    0.306179775280899, 0.160958904109589, 0.243150684931507,
    0.595890410958904)), .Names = c("A", "B", "Freq"), class = "data.frame", row.names = c(NA,
-9L))

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

enter image description here

I could not figure out how to put the numbers in the right position along x-axis. Any help will be highly appreciates. Thanks

like image 297
MYaseen208 Avatar asked Feb 07 '12 22:02

MYaseen208


1 Answers

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

like image 165
Brian Diggs Avatar answered Oct 05 '22 21:10

Brian Diggs