How to Make Faceted Ordered Bar Charts in R

Master R

By Guangming Lang Comment

Previously, I showed how to make ordered bar charts using ggplot2. Sometimes, you want to create multiple facets and put on each facet an ordered bar chart. Here’s how you can do that using ggplot2.


# make fake data
df = data.frame(val = rnorm(10, mean=5),
                cat = gl(5, 2, labels = letters[1:5, drop=T]),
                group = gl(2, 1, 10, labels = c("group1", "group2")))

# combine cat and group into a new factor called
df = transform(df, = factor(paste(group, cat)))

# reorder the levels of by the increasing order of val
df = transform(df, = reorder(, rank(val)))

# make barplot
ggplot(df, aes(, val)) +
        geom_bar(aes(fill = cat), stat = "identity") +
        facet_grid(. ~ group, scales = "free_x") +
        scale_x_discrete(labels=df$cat, breaks=df$ + 
        labs(x = "", size=2)


If you enjoyed this post, get updates. It's FREE