A line chart is a type of chart which showcases information as a sequency of data points also known as 'markers' which are connected by staright line. It is mainly used to plot the relationship or trend of a categorical variable with respect to a numerical variable.
In this recipe we are going to use ggplot2 package to plot the required Line Chart. ggplot2 package is based on the book "Grammar of Graphics" by Wilkinson. This package provides flexibility while incorporating different themes and plot specification with a high level of abstraction. The package mainly uses aesthetic mapping and geometric objects as arguments. Different types of geometric objects include:
The basic syntax of gggplot2 plots is:
ggplot(data, mapping = aes(x =, y=)) + geometric object
This recipe demonstrates how to make a Line Chart using ggplot2.
We will use an example of no of schools established in 2 states between 1970 and 2014
# Data manipulation package library(tidyverse) # ggplot for data visualisation library(ggplot2) # years year = c('1970','1980', '1990', '2000', '2013', '2014') #no of schools in state1 corresponding to a particular year no_of_schools_state1 = c(15, 30, 60, 120, 240, 300) #creating a dataframe df = data.frame(year_x,state_y1) df
1970 15 1980 30 1990 60 2000 120 2013 240 2014 300
We use geometric object as geom_line() to plot a line chart between two variables (Age and Customer ID)
ggplot(df, mapping = aes(x = year, y = no_of_schools_state1, group = 1)) + geom_line() + labs(title = "No of schools vs Year")