corrado
corrado

Reputation: 135

Comparing proportions in ggplot2

I have a dataframe df like this one:

Id    Var1    Var2    Var3
001   yes     no      yes
002   no      no      yes
003   yes     yes     no

I want to create a barplot with 3 bars that represents proportions of yesand nofor Var1 Var2 Var3. Is it possible to do that with ggplotwithout reshaping the dataframe?

Thank you,

corrado

Upvotes: 0

Views: 1483

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98419

As it was already mentioned it is better to reshape data.

But if you need to use original data frame then you should use geom_bar() for each column you want to appear on plot. In geom_bar() you should provide x values that will separate those bars - I used variable names as characters. fill= and position="stack" ensures that bars are stacked. y=(..count..)/sum(..count..)) will calculate proportions.

df <- read.table(text=
"Id    Var1    Var2    Var3
 001   yes     no      yes
 002   no      no      yes
 003   yes     yes     no",header=T)

library(scales)
library(ggplot2
ggplot(df)+
  geom_bar(aes(x="Val1",fill=Var1,y=(..count..)/sum(..count..)),position="stack")+
  geom_bar(aes(x="Val2",fill=Var2,y=(..count..)/sum(..count..)),position="stack")+
  geom_bar(aes(x="Val3",fill=Var3,y=(..count..)/sum(..count..)),position="stack")+
  scale_y_continuous("Percents",labels = percent) + 
  scale_x_discrete("Values")+
  scale_fill_discrete("Legend_title")

enter image description here

Upvotes: 1

Related Questions