0

I am trying to plot a simple bar chart with labels in ggplot2. However, when I use position=dodge, it puts the wrong labels in the resulting graphic, eg. 17.6% instead of 77.7% for Trucks. My data and code are below.

library(ggplot2)

mode <- factor(c("Truck", "Rail","Water","Air","Other"), levels=c("Truck", "Rail","Water","Air","Other"))
Year <- factor(c("2011","2011","2011","2011","2011","2040","2040","2040","2040","2040"))
share <- c(0.709946085, 0.175582806, 0.11392987, 0.000534132, 0.00000710797, 0.777162621, 0.133121584, 0.088818658, 0.000880041, 0.000017097)
modeshares <- data.frame(Year, mode, share)

theme_set(theme_grey(base_size = 18)) 

modeshares$lab <- as.character(round(100 * share,1))
modeshares$lab <- paste(modeshares$lab,"%",sep="")

ggplot(data=modeshares, aes(x=mode, y=share*100, fill=Year, ymax=(share*100))) + geom_bar(stat="identity", position="dodge") + labs(y="Percent",x="Mode") +geom_text(label=modeshares$lab,position=position_dodge(width=1),vjust=-0.5)

The resulting graph is shown below. Modeshares

Any insights into how to ensure that the correct label values are displayed would be much appreciated.

Thanks!

tonytonov
  • 25,060
  • 16
  • 82
  • 98
Krishnan
  • 1,265
  • 2
  • 13
  • 24
  • 3
    You need to fix your mapping. The `modeshares$lab` puts them in the order that they appear in the data frame. Change the last geom to `geom_text(data = modeshares, aes(label = lab), position=position_dodge(width=1), vjust=-0.5)` – rawr Mar 20 '14 at 21:08
  • @rawr That sounds suspiciously like an answer. :) – joran Mar 20 '14 at 21:10

0 Answers0