Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 Labeling a multilayered bar plot

Tags:

r

ggplot2

What I'd like to do is label both of the geom_bar() 's in the following example with their respective data labels. So far, I can only get one or the other to show up:

dput():

x <- structure(list(variable = c("a", "b", "c"), f = c(0.98, 0.66, 
0.34), m = c(0.75760989010989, 0.24890977443609, 0.175125)), .Names = c("variable", 
"f", "m"), row.names = c(NA, 3L), class = "data.frame")

ggplot(x, aes(variable, f, label=paste(f*100,"%", sep=""))) + 
geom_bar() + 
geom_text(size=3, hjust=1.3, colour="white") +
geom_bar(aes(variable, m, label=paste(m*100,"%",sep="")), fill="purple") + 
coord_flip()

Multilayered Bar Graph

See how on the inside of the black there is a data label. In the same plot, I'd like to do the same thing on the inside of the purple.

like image 252
Brandon Bertelsen Avatar asked Sep 27 '10 22:09

Brandon Bertelsen


2 Answers

how does this work for you:

ggplot(x, aes(variable, f, label=paste(f*100,"%", sep=""))) + 
geom_bar() + 
geom_text(size=3, hjust=1.3, colour="white") +
geom_bar(aes(variable, m, label=paste(m*100,"%",sep="")), fill="purple") + 
geom_text(aes(y=m,label=paste(round(m*100),"%",sep="")),size=3, hjust=1.3, colour="white") +
coord_flip()
like image 139
Ian Fellows Avatar answered Nov 18 '22 21:11

Ian Fellows


You may want to consider a different approach.

If the main goal of the graph is to compare the lengths/positions of the bars, then including numbers in the bars produces "fuzzy" bars making it harder for the eye/brain to properly judge the length/position of the bar.

If the main goal is to compare the numbers, then what you have is a poorly laid out table (with colorful background), it is easier to compare the numbers if they line up properly.

Some alternatives would include having a seperate graph and table (both properly laid out), or put the numbers in the margin (properly aligned) rather than on top of the bars, or create a table with barplots in marginal cells. You may also want to consider a dot plot rather than a bar plot (ggplot2 should still do this easily), stacked bars allow reasonable comparison of only the 1st (leftmost) category and the total, in your example it is not easy to compare the relative size of the black portion of the top and bottom bars.

like image 34
Greg Snow Avatar answered Nov 18 '22 23:11

Greg Snow