0

I have a problem with drawing stacked barplot with ggplot. My data looks like this:

timeInterval TotalWilling TotalAccepted SimID
 1           16            12            Sim1
 1           23            23            Sim2
 1           63            60            Sim3
 1           69            60            Sim4
 1           61            60            Sim5
 1           60            54            Sim6
 2           16             8            Sim1
 2           23            21            Sim2
 2           63            52            Sim3
 2           69            64            Sim4
 2           61            45            Sim5
 2           60            32            Sim6
 3           16            14            Sim1
 3           23            11            Sim2
 3           63            59            Sim3
 3           69            69            Sim4
 3           61            28            Sim5
 3           60            36            Sim6

I would like to draw a stacked barplot for each simID over a timeInterval, and Willing and Accepted should be stacked. I achieved the barplot with the following simple code:

dat <- read.csv("myDat.csv")
meltedDat <- melt(dat,id.vars = c("SimID", "timeInterval"))
ggplot(meltedDat, aes(timeInterval, value,  fill = variable)) +  facet_wrap(~ SimID) +
geom_bar(stat="identity", position = "stack")

I get the following graph: enter image description here

Here my problem is that I would like to put percentages on each stack. Which means, I want to put percentage as for Willing label: (Willing/(Willing+Accepted)) and for Accepted part, ((Accepted/(Accepted+Willing)) so that I can see how many percent is willing how many is accepted such as 45 on red part of stack to 55 on blue part for each stack. I cannot seem to achieve this kind of labeling.

Any hint is appreciated.

Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89
kukushkin
  • 312
  • 4
  • 16

1 Answers1

0

applied from Showing data values on stacked bar chart in ggplot2

meltedDat <- melt(dat,id.vars = c("SimID", "timeInterval"))
meltedDat$normvalue <- meltedDat$value
meltedDat$valuestr <- sprintf("%.2f%%", meltedDat$value, meltedDat$normvalue*100)
meltedDat <- ddply(meltedDat, .(timeInterval, SimID), transform, pos = cumsum(normvalue) - (0.5 * normvalue))
ggplot(meltedDat, aes(timeInterval, value,  fill = variable)) +  facet_wrap(~ SimID) + geom_bar(stat="identity", position = "stack") + geom_text(aes(x=timeInterval, y=pos, label=valuestr), size=2)

also, it looks like you may have some of your variables coded as factors.

Community
  • 1
  • 1
fanli
  • 1,069
  • 7
  • 13
  • This does not serve what I would like to do but I can play with it to transform to the way I want. Thanks a lot for the hint. @fanli – kukushkin Mar 28 '16 at 18:52