Multiple Bar Charts in R

By Data Tricks, 26 February 2020

Last modified 26 February 2020

First let’s run some code to create an example dataset and set the theme for our charts.

rm(list=ls())
library(ggplot2)

set.seed(515)
data <- data.frame(
        Year = rep(c(1:10), each = 1, times = 4),
        Value = c(sample(30:100, 10), sample(30:100, 10), sample(30:100,10), sample(30:100,10)),
        Category = rep(c("One", "Two", "Three", "Four"), each=10, times=1)
        )
levels(data$Category) <- c("One","Two","Three","Four")
theme <- theme(panel.grid.major = element_blank(),
               panel.grid.minor = element_blank(),
               panel.background = element_blank(),
               axis.line.x = element_line(color="#919191", size = 0.1),
               axis.line.y = element_line(color="#919191", size = 0.1)
               )

Note that we have added a line of code beginning with levels(data$Category) to reorder the factor levels of the Category column. This is useful when you are trying to product ggplots with factor variables as the default order will usually be alphabetical.

Stacked Bar Chart

gg <- ggplot(data)
gg <- gg + geom_bar(aes(x = Year, y = Value, fill = Category), position = "stack", stat = "identity")
gg <- gg + scale_x_continuous(breaks=c(1:10))
gg <- gg + theme
print(gg)

Stacked Bar Chart (percentage of whole)

gg <- ggplot(data)
gg <- gg + geom_bar(aes(x = Year, y = Value, fill = Category), position="fill", stat = "identity")
gg <- gg + scale_x_continuous(breaks=c(1:10))
gg <- gg + theme
print(gg)

Grouped Bar Chart

gg <- ggplot(data)
gg <- gg + geom_bar(aes(x = Year, y = Value, fill = Category), position="dodge", stat = "identity")
gg <- gg + scale_x_continuous(breaks=c(1:10))
gg <- gg + theme
print(gg)

Bar charts with facets in R

gg <- ggplot(data)
gg <- gg + geom_bar(aes(x = Year, y = Value, fill = Category), position = "stack", stat = "identity")
gg <- gg + scale_x_continuous(breaks=c(1:10))
gg <- gg + theme
gg <- gg + facet_grid(~Category)
print(gg)

Bar Charts in a Grid

gg <- ggplot(data)
gg <- gg + geom_bar(aes(x = Year, y = Value, fill = Category), position = "stack", stat = "identity")
gg <- gg + scale_x_continuous(breaks=c(1:10))
gg <- gg + theme
gg <- gg + facet_wrap(~Category)
print(gg)

Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Please note that your first comment on this site will be moderated, after which you will be able to comment freely.