Line Chart using Base R

We have covered some of the Base R graphic elements in the last blog - Elements of Base R Graphics

Some of the points discussed and explained in the blogs are:

  • Diffferent type & style of lines
  • Adding Vertical or Horizontal Lines
  • Plot mulitple lines
  • Add and change position of legend
  • Change position of y axis label to right and x axis label to above

par(mgp=c(axis.title.position, axis.label.position, axis.line.position))

Remove spacing around plotting area in r

# Set up library
setwd("~/Learn R/training")
# Read data
london <- read.csv("londonT.csv")
names(london) ##  [1] "X.1"        "X"          "Name"       "Country"    "Age"       
##  [6] "Height"     "Weight"     "Sex"        "DOB"        "Place_dob" 
## [11] "Gold"       "Silver"     "Bronze"     "Total"      "Sport"     
## [16] "Event"      "WeightNorm" "HeightNorm" "cluster" # Create Groups/factors
Height.Grp <- cut(london$Height, breaks=c(160,170,180,190,300),labels=c("Low-170","170-180","180-190","190-High"))
# Summarize weights by Height Factors
mean.weight <- aggregate(london$Weight,by=list(Height.Grp),mean)
names(mean.weight) <-c("HeightGroup","Avg.Weight")

Simple Line Chart

type parameter in plot function has multiple options. if type=“b” is selected, the plot will have both plotting character and line connector. If type=“c”, then line part along and type=“l” will plot a line connecting all the points

par(mfrow=c(1,3))
plot( mean.weight$Avg.Weight, 
     col="red",
     xlab="Height Level",
     ylab="Mean Weight",
     pch=20,
     type="b" 
     )
plot( mean.weight$Avg.Weight, 
     col="red",
     xlab="Height Level",
     ylab="Mean Weight",
     pch=20,
     type="c" 
     )
plot( mean.weight$Avg.Weight, 
     col="red",
     xlab="Height Level",
     ylab="Mean Weight",
     pch=20,
     type="l" 
     )

linechart

Diffferent type & style of lines

plot function as multiple options to change line properties.

lwd : change line width

lty : Change line type and takes integer value between 0 and 6 0=blank 1=solid (default) 2=dashed 3=dotted 4=dotdash 5=longdash 6=twodash

col : Line color.

 

par(mfrow=c(1,3))
# Change line Properies: Width
plot( mean.weight$Avg.Weight, 
     col="red",
     xlab="Height Level",
     ylab="Mean Weight",
     pch=20,
     type="l" ,
     lwd=4   # line width
     )
plot( mean.weight$Avg.Weight, 
     col="red",
     xlab="Height Level",
     ylab="Mean Weight",
     pch=20,
     type="l" ,
     lwd=3,   # line width
     lty=5    # Line type
     )
plot( mean.weight$Avg.Weight, 
     col="blue", # Line color
     xlab="Height Level",
     ylab="Mean Weight",
     pch=20,
     type="l" ,
     lwd=3,   # line width
     lty=5    # Line type
     )

linechart v1

Adding Vertical or Horizontal Lines

abline function can help in drawing a vertical line or horizontal line. This has two options h for horizontal line(s) and v for vertical line(s).

 

par(mfrow=c(1,3))
# Horizontal Line
# Calculate mean values for horizontal line
h1 <- mean(mean.weight$Avg.Weight)
# plot line graph
plot( mean.weight$Avg.Weight, 
     col="red",
     xlab="Height Level",
     ylab="Mean Weight",
     pch=20,
     type="l" ,
     lwd=4   # line width
     )
abline(h=h1)
# Vertical Line
v1  <- 2
plot( mean.weight$Avg.Weight, 
     col="red",
     xlab="Height Level",
     ylab="Mean Weight",
     pch=20,
     type="l" ,
     lwd=3,   # line width
     lty=5    # Line type
     )
abline(v=v1)
## Draw both horizontal and vertical
plot( mean.weight$Avg.Weight, 
     col="blue", # Line color
     xlab="Height Level",
     ylab="Mean Weight",
     pch=20,
     type="l" ,
     lwd=3,   # line width
     lty=5    # Line type
     )
abline(h=h1)
abline(v=v1)

linechart v2

Plot mulitple line plots in R

Scenario of requiring multiple line charts.

A retailer sells various products across categories. We want to plot sales volumne trend of various product categories. Two product categories - Groce..

We want to compare sales volume of categories across period. Multiple Line or Dataseries plot can help in visualizing the trends.

# sample data creation
year <- c(1988,  1989,  1990,   1991,   1992,   1993,   1994,   1995,   1996,   1997)
babystore <- c(49.9,  53.7, 57.2,   57.8,   58.8,   61.4,   64.1,   65.4,   69.2,   73.3)
clothing <- c(45.5,  48.6,  52.2,   52.1,   52.2,   54.5,   57.3,   58.6,   60.8,   65)
food <- c(60.8,  63.7,  65.8,   65.4,   65, 69.4,   71.6,   72.7,   78.3,   85.3)
retail.sales <- data.frame(year, babystore, clothing, food)
names(retail.sales) ## [1] "year"      "babystore" "clothing"  "food"

par has a parameter new and if set to TRUE, it will plot the graph in the same plotting frame without resetting.

For avoiding re-labelling of x axis and y axis for subsequent plot, the label should be marked as blank.

Add and change position of legend

legend can be add to the graph using legend function. topleft, left, center, right, righttop and few other are options to decide the position of the legend.

We can also provide x and y values as position of the legend.

par(mfrow=c(1,1))
# first line plot
plot(x=retail.sales$year, 
     y=retail.sales$babystore,
     col="blue", # Line color
     xlab="Year",
     ylab="Sales",
     pch=20,
     type="l" ,
     lwd=3,   # line width
     lty=1    # Line type
     )
# Second Line
par(new=T)
plot(x=retail.sales$year, 
     y=retail.sales$clothing,
     col="red", # Line color
     axes=F,
     pch=20,
     xlab='',
     ylab='',
     type="l" ,
     lwd=3,   # line width
     lty=1    # Line type
     )
par(new=T)
plot(x=retail.sales$year, 
     y=retail.sales$food,
     col="green", # Line color
     axes=T,
     xlab='',
     ylab='',
     pch=20,
     type="l" ,
     lwd=3,   # line width
     lty=1    # Line type
     )
#add legend
legend( 'topleft',legend=c("Baby Store","Clothing","Food"),
        col=c("blue","red","green"),
        lty=c(1,1,1),
        cex=0.6)

 

linechart v3

Some of the other useful blogs on visualizations using R

 

 

4 thoughts on “Line Chart using Base R”

Leave a Comment