3

Someone already explained stacked bars within grouped bar chart here

test <- data.frame(person = c("group 1", "group 2", "group 3"), 
                   value1 = c(100, 150, 120),  # male   
                   value2 = c(25, 30, 45) ,    # female
                   value3 = c(25, 30, 45),     # male
                   value4 = c(100, 120, 150),  # female
                   value5 = c(10, 12, 15),     # male
                   value6 = c(50, 40, 70))     # female

library(reshape2) # for melt

melted <- melt(test, "person")

melted$cat <- ''
melted[melted$variable == 'value1' | melted$variable == 'value2',]$cat <- "sub group 1"
melted[melted$variable == 'value3' | melted$variable == 'value4',]$cat <- "sub group 2"
melted[melted$variable == 'value5' | melted$variable == 'value6',]$cat <- "sub group 3"
melted$gender <- ''
melted[melted$variable %in% sprintf("value%i",c(1,3,5)),]$gender <- "female"
melted[melted$variable %in% sprintf("value%i",c(2,4,6)),]$gender <- "male"


p = ggplot(melted, aes(x = cat, y = value, fill = gender)) 

p + 
  geom_bar(stat = 'identity', position = 'stack') +   
  facet_grid(~ person) + 
  scale_fill_manual(values = c("orangered","dodgerblue2")) + 
  theme(panel.background = element_rect(fill = 'white'))

I want to add another group but no subgroups within that group. is there any command or function that can do that in ggplot2?

thank you

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
Tevfik K
  • 33
  • 2

1 Answers1

3

Assuming you have it all in one dataset, you can reuse your current code with only minor additions in the facet_grid() line:

melted2 <- rbind(melted,
                 data.frame(person = rep("group 4", times = 2),
                            variable = NA,
                            value = c(80, 20),
                            cat = "no subgroup",
                            gender = c("female", "male")))    

ggplot(melted2, 
       aes(x = cat, y = value, fill = gender)) + 
  geom_col(position = 'stack') +   # geom_col() is equivalent to geom_bar(stat = "identity")
  facet_grid(~ person, scales = "free_x", space = "free_x") +
  scale_fill_manual(values = c("orangered", "dodgerblue2")) + 
  theme(panel.background = element_rect(fill = 'white'))

plot

scales = "free_x" tells each facet to only show cat values that appear in that facet. space = "free_x" adjusts the size of each facet accordingly so all the bars are the same width.

Z.Lin
  • 28,055
  • 6
  • 54
  • 94