Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@aravindhebbali
Last active September 26, 2017 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aravindhebbali/57f3c568170ae29ed9cde9f54713269c to your computer and use it in GitHub Desktop.
Save aravindhebbali/57f3c568170ae29ed9cde9f54713269c to your computer and use it in GitHub Desktop.
Data Visualization: Bar Plots
# using plot function
plot(as.factor(mtcars$cyl))
# using bar plot function
barplot(table(mtcars$cyl))
# tabulated data
cyl_freq <- table(mtcars$cyl)
cyl_freq
# horizontal bar plot
barplot(cyl_freq, horiz = TRUE)
# bar width
# equal width
barplot(cyl_freq, width = 2)
# different widths
barplot(cyl_freq, width = c(1, 1, 2))
# space between bars
barplot(cyl_freq, space = c(1, 1, 2))
# bar labels
barplot(cyl_freq, names.arg = c('Four', 'Six', 'Eight'))
# bar color
barplot(cyl_freq, col = 'blue')
barplot(cyl_freq, col = c('blue', 'red', 'green'))
barplot(cyl_freq, col = c('blue', 'red'))
# bar border color
barplot(cyl_freq, border = 'blue')
# remove axes
barplot(cyl_freq, axes = FALSE)
# axis line type
barplot(cyl_freq, axis.lty = 3)
# offset axes
barplot(cyl_freq, offset = 5)
# putting it all together
barplot(cyl_freq, col = c('blue', 'red', 'green'),
horiz = TRUE, width = c(1, 1, 2),
names.arg = c('Four', 'Six', 'Eight'),
axis.lty = 2, offset = 2)
# title and axis labels
barplot(cyl_freq, col = c('blue', 'red', 'green'),
horiz = TRUE, width = c(1, 1, 2),
names.arg = c('Four', 'Six', 'Eight'),
axis.lty = 2, offset = 2)
title(main = 'Distribution of Cylinders',
xlab = 'Frequency', ylab = 'Number of Cylinders')
# bivariate plot data
table(mtcars$gear)
cyl_gear <- table(mtcars$cyl, mtcars$gear)
cyl_gear
# stacked bar plot
barplot(cyl_gear)
# bar colors
barplot(cyl_gear, col = c('blue', 'red', 'green'))
# add legend
barplot(cyl_gear, col = c('blue', 'red', 'green'),
main = 'Gears vs Cylinders', legend.text = TRUE,
xlab = 'Number of Gears', ylab = 'Frequency')
# grouped bar plot
barplot(cyl_gear, col = c('blue', 'red', 'green'),
beside = TRUE, legend.text = TRUE,
main = 'Gears vs Cylinders',
xlab = 'Number of Gears', ylab = 'Frequency')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment