Bogaso
Bogaso

Reputation: 3308

Add group information in multiple bar chart with ggplot

Let say I have below multiple bar chart with ggplot

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] 

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level
Names=c("Food","Music","People")     
data=data.frame(cbind(freq),Names)   
data=data[,c(5,3,1,2,4)]             


data.m <- melt(data, id.vars='Names')


ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

This is fine. However I want to add some group information along the x-axis. Let say 2 groups are defined as Group1 : Food and Music and Group2 : People. With this, I am trying build a ggplot like below

enter image description here

I also want to reduce the space between Food & Music and increase the space between Music & People - just to demonstrate Food & Music form 1 group and People another group.

Is there any way to achieve this using ggplot framework?

Upvotes: 3

Views: 52

Answers (1)

stefan
stefan

Reputation: 124013

There are several options like adding the group information as annotations to your plot. But IMHO a good starting point and the simplest approach would be to use faceting:

Using some fake example data:

library(ggplot2)

variable <- c("Very Bad","Bad","Good","Very Good")

data.m <- data.frame(
  Names = rep(c("Food","Music","People"), each = 4),
  value = 1:12,
  variable = factor(variable, levels = variable)
)
data.m$group <- ifelse(data.m$Names %in% c("Food", "Music"), "Group 1", "Group 2")

ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity") +
  facet_grid(.~group, space = "free", scales = "free_x", switch = "x") +
  theme(strip.placement = "outside",
        strip.background.x = element_rect(fill = NA),
        strip.text.x = element_text(color = "red"))

Upvotes: 4

Related Questions