Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make frequency barplot in groups?

Suppose my data is two columns, one is "Condition", one is "Stars"

food <- data.frame(Condition = c("A", "B", "A", "B", "A"), Stars=c('good','meh','meh','meh','good'))

How to make a barplot of the frequency of "Star" as grouped by "Condition"?

I read here but would like to expand that answer to include groups.

for now I have

q <- ggplot(food, aes(x=Stars))
q + geom_bar(aes(y=..count../sum(..count..)))

enter image description here but that is the proportion of the full data set.

How to make a plot with four bars, that is grouped by 'Condition'?

Eg. 'Condition A' would have 'Good' as 0.66 and 'Meh' as 0.33

like image 328
kevin0228ca Avatar asked Aug 16 '17 09:08

kevin0228ca


2 Answers

I guess this is what you are looking for:

food <- data.frame(Condition = c("A", "B", "A", "B", "A"), Stars=c('good','meh','meh','meh','good'))
library(ggplot2)
library(dplyr)
data <- food %>% group_by(Stars,Condition) %>% summarize(n=n()) %>% mutate(freq=n/sum(n)) 

ggplot(data, aes(x=Stars, fill = Condition, group = Condition)) + geom_bar(aes(y=freq), stat="identity", position = "dodge")

enter image description here

At first i have calculated the frequencies using dplyr package, which is used as y argument in geom_bar(). Then i have used fill=Condition argument in ggplot() which divided the bars according to Condition. Additionally i have set position="dodge" to get the bars next to each other and stat="identity", due to already calculated frequencies.

like image 111
Mal_a Avatar answered Oct 19 '22 09:10

Mal_a


I have used value ..prop.., aesthetic group and facet_wrap(). Using aesthetic group proportions are computed by groups. And facet_wrap() is used to plot each condition separately.

require(ggplot2)

food <- data.frame(Condition = c("A", "B", "A", "B", "A"),
                   Stars=c('good','meh','meh','meh','good'))

ggplot(food) +
  geom_bar(aes(x = Stars, y = ..prop.., group = Condition)) +
  facet_wrap(~ Condition)

enter image description here

like image 3
djhurio Avatar answered Oct 19 '22 10:10

djhurio