In this notebook, we will be focusing on creating a barplot in R. As a first step, we will be loading the dataframe and create a table from it.
df <- read.csv('Data/NHANES.csv')
head(df)
count <- table(df$Education)[2:6]
count
##
## 8th Grade 9 - 11th Grade College Grad High School Some College
## 451 888 2098 1517 2267
We will be using this table to create a barplot. The basic structure of the code to create a barplot is the following:
barplot(count, xlab='x axis label', main='title')
where count
is the table that is created by using the dataframe. xlab
is the x-axis label and main
is the title of the plot.
barplot(count, xlab='Education level', main='Education in the U.S.')
We can easily reorder the barplot by creating levels inside the dataframe. This can be done by using the following code:
df$Education <- factor(df$Education, levels=c('8th Grade','9 - 11th Grade','High School','Some College','College Grad'))
count <- table(df$Education)
count
##
## 8th Grade 9 - 11th Grade High School Some College College Grad
## 451 888 1517 2267 2098
We at first factor the items in the column by using:
df$column <- factor(df$column, levels=c('element1','element2',...))
where you put element1
, element2
, …, based on the order that you would like to show it on the barplot. Then, create a table from that column and make a barplot from the new table:
barplot(count, xlab='Education level', main='Education in the U.S.')
We can change the color of the barplot by adding a col
argument inside the code:
barplot(count, xlab='x axis label', main='title', col=`blue`)
change blue
based on the color that you would like to have. The list of main colors available in R is:
https://www.r-graph-gallery.com/42-colors-names.html
http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf
barplot(count, xlab='Education level', main='Education in the U.S.', col='cyan')
©2021 by Daiki Tagami. All rights reserved.