R Line Plot

A line plot is a graph that connects a series of points by drawing line segments between them. These points are ordered in one of their coordinate (usually the x-coordinate) value. Line plots are usually used in identifying the trends in data. R Line plot is created using The plot() function

Syntax R Line plot

The basic syntax to create a line plot in R is:

plot(v,type,col,xlab,ylab)

Following is the description of the parameters used:

  • v is a vector containing the numeric values.
  • type takes the value “p” to draw only the points, “l” to draw only the lines and “o” to draw both points and lines.
  • xlab is the label for x axis.
  • ylab is the label for y axis.
  • main is the Title of the chart.
  • col is used to give colors to both the points and lines.

Example for Line Plot in R

A simple line plot in R is created using the input vector and the type parameter as “O”.

# R line plot
v <- c(8,14,26,5,43)
plot(v,type="o")

When we execute the above code, it produces the following result:

r line plot

R Line Plot with Title, Color and Labels

The features of the line plot can be expanded by using additional parameters. We add color to the points and lines, give a title to the chart and add labels to the axes by making following changes to the above script.

v <- c(8,14,26,5,43)
plot(v,type="o",col="blue",xlab="Month",ylab="Rain fall",main="Rain fall chart")

When we execute the above code, it produces the following result:

r line plot with labels

Multiple Lines in a R Line Plot:

More than one line can be drawn on the same chart by using the lines() function. After the first line is plotted, the lines() function can use an additional vector as input to draw the second line in the chart.

v <- c(8,14,26,5,43)
t <- c(14,7,8,10,13)
plot(v,type="o",col="blue",xlab="Month",ylab="Rain fall",main="Rain fall chart")
lines(t, type="o", col="red")

When we execute the above code, it produces the following result:

r line plot with multiple lines

previous small r line plot                                                                                                         next small r line plot

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.