0
votes

I was looking for an answer everywhere, but I just couldn't find one to this problem (maybe I was just too stupid to use other answers, because I'm new to R).

I have two data frames with different numbers of rows. I want to create a plot containing a single bar per data frame. Both should have the same length and the count of different variables should be stacked over each other. For example: I want to compare the proportions of gender in those to data sets.

t1<-data.frame(cbind(c(1:6), factor(c(1,2,2,1,2,2)))) t2<-data.frame(cbind(c(1:4), factor(c(1,2,2,1))))

1 represents male, 2 represents female I want to create two barplots next to each other that represent, that the proportions of gender in the first data frame is 2:4 and in the second one 2:2.

My attempt looked like this:

ggplot() + geom_bar(aes(1, t1$X2, position = "fill")) + geom_bar(aes(1, t2$X2, position = "fill"))

That leads to the error: "Error: stat_count() must not be used with a y aesthetic."

1
Please read this stackoverflow.com/help/mcve and edit your question accordingly. You can provide your date by using the function dput in order to make your problem reproducible.Alex

1 Answers

1
votes

First I should merge the two dataframes. You need to add a variable that will identify the origin of the data, add in both dataframes a column with an ID (like t1 and t2). Keep in mind that your columnames are the same in both frames so you will be able to use the function rbind.

t1$data <- "t1"
t2$data <- "t2"
t <- (rbind(t1,t2))

Now you can make the plot:

ggplot(t[order(t$X2),], aes(data, X2, fill=factor(X2))) +        
geom_bar(stat="identity", position="stack")