AppleGate0
AppleGate0

Reputation: 335

Two Variable side by side bar plot ggplot of categorical data

demo <- read.table(header = TRUE,
               text ="var1 Var2
               Good Excellent
               Subpar Good
               Excellent Decent
               Good Good
               Subpar Subpar")

How would I create a side by side bar plot these Var1 and Var2 where the Y-axis is the count of each of each distinct values?

For instance a bar under good comparing the number of good in var1 to var2?

Upvotes: 1

Views: 2065

Answers (2)

Prem
Prem

Reputation: 11955

library(reshape)
library(ggplot2)

#sample data    
demo <- read.table(header = TRUE,
                   text ="var1 var2
                   Good Excellent
                   Subpar Good
                   Excellent Decent
                   Good Good
                   Subpar Subpar")

#pre-processing
df <- merge(melt(table(demo$var1)), melt(table(demo$var2)), by='Var.1', all=T)
colnames(df) <- c("Words", "Var1", "Var2")
df[is.na(df)] <- 0
df <- melt(df, id=c("Words"))
colnames(df) <- c("Words", "Column_Name", "Count")

#plot
ggplot(df, aes(x=Words, y=Count, fill=Column_Name)) +
  geom_bar(position="dodge", stat="identity")

Final Plot

Upvotes: 1

Roman
Roman

Reputation: 17648

The tidyverse is perfect for that:

library(tidyverse)
demo %>% 
  gather(key, value) %>% 
  mutate(value_ordered = factor(value, levels=c("Decent","Good", "Subpar", "Excellent"))) %>% 
  ggplot(aes(value_ordered, fill=key)) +
           geom_bar(position="dodge")

enter image description here

Or bars with same width:

as.tbl(demo) %>% 
  gather(key, value) %>% 
  group_by(key, value) %>%   # group
  count() %>%    # count the frequency
  ungroup() %>%  # ungroup
  complete(key, value) %>%  # Complete missing combinations 
  mutate(value_ordered = factor(value, levels=c("Decent","Good", "Subpar", "Excellent"))) %>% 
  ggplot(aes(value_ordered,n, fill=key)) +
    geom_col(position = "dodge")   # it is recommended to use geom_col directly instead of stat="identity"

Upvotes: 1

Related Questions