I have problems filling the bars while grouping with facet_wrap Using this data.frame:
library(ggplot2)
library(gridExtra)
set.seed(1234)
testDat <- data.frame(answer=factor(sample(c("yes", "no"), 60, replace=TRUE)),
which=factor(sample(c("q1", "q2", "q3"), 60, replace=TRUE)))
I wanted to plot the answer grouped by the variable which. This gives me the absolute values:
ggplot(testDat, aes(x=answer)) +
geom_bar(aes(fill=answer)) + facet_wrap(~which)
This gives me the relative values. But not per group:
ggplot(testDat, aes(x=answer)) +
geom_bar(aes(y=(..count..)/sum(..count..), fill=answer)) + facet_wrap(~which)
Searching for an answer I detected this to plot the relative values per group. But the fill color doesn't work anymore
ggplot(testDat, aes(x=answer)) +
geom_bar(aes(y=(..count..)/sum(..count..), group=which, fill=answer)) + facet_wrap(~which)
It just works for the three different values of 'which' and not of 'answer'
ggplot(testDat, aes(x=answer)) +
geom_bar(aes(y=(..count..)/sum(..count..), group=which, fill=which)) + facet_wrap(~which)
Any suggestions for how to fill the bars?
p1<-ggplot(testDat, aes(x=answer)) + geom_bar(aes(y=(..count..)/sum(..count..), group=which, fill=answer)) + facet_wrap(~which)
p2<-ggplot(testDat, aes(x=answer)) + geom_bar(aes(y=(..count..)/sum(..count..), group=which, fill=which)) + facet_wrap(~which)
grid.arrange(p1,p2)