Bar charts in R with ggplot2

By Data Tricks, 23 July 2018

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

library(ggplot2)
set.seed(535)

data <- data.frame(Year = c(1:10), Value = sample(30:100, 10), Weight = sample(2:7, 10, replace = TRUE))

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)
)

Simple bar chart

#Basic bar chart
gg <- ggplot(data)
gg <- gg + geom_bar(aes(x = Year, y = Value), stat = "identity")
gg <- gg + theme
print(gg)

Custom colour bar chart

#Custom colour bar chart
gg <- ggplot(data)
gg <- gg + geom_bar(aes(x = Year, y = Value), fill="#62a4d1", stat = "identity")
gg <- gg + ggtitle(paste("My chart"))
gg <- gg + theme
gg <- gg + theme(plot.title = element_text(size=16, face="bold", hjust = 0.5),
axis.ticks=element_blank(),
panel.grid=element_blank(),
panel.border=element_blank()
)
print(gg)

Bar chart with variable widths

#Bar chart with variable widths
data$right <- cumsum(data$Weight) + c(0:(nrow(data)-1))
data$left <- data$right - data$Weight
gg <- ggplot(data)
gg <- gg + geom_rect(aes(xmin = left, xmax = right, ymin = 0, ymax = Value), fill="#62a4d1", stat = "identity")
gg <- gg + ggtitle(paste("My chart"))
gg <- gg + theme
gg <- gg + theme(plot.title = element_text(size=16, face="bold", hjust = 0.5),
axis.ticks=element_blank(),
axis.text.x=element_blank(),
panel.grid=element_blank(),
panel.border=element_blank()
)
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.