EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

Line Graph in R

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » R Programming Tutorial » Line Graph in R

line graph in R

Introduction to Line Graph in R

Line Graph in R is a basic chart in R language which forms lines by connecting the data points of the data set. Line charts can be used for exploratory data analysis to check the data trends by observing the line pattern of the line graph. Line Graph is plotted using plot function in the R language. The line graph can be associated with meaningful labels and titles using the function parameters. The line graphs can be colored using the color parameter to signify the multi-line graphs for better graph representation. The line graphs in R are useful for time-series data analysis.

Fig 1. Shows the basic line graph, where value is the “event count” over a year. The x-axis depicts the time, whereas the y-axis depicts the “event count”.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Line graphFig 1 -Line graph

One can get to know trend, seasonality related to data by plotting line graph.

The basic syntax to draw a line chart in R:

plot(vec,type,xlabel,ylabel)
vec: This is the vector, which has numeric values to be plotted
type: Its of three “p”, ”l” and “o”
p: It draws only points
l:It draws only line
o:It draws point as well as line
xlabel: Its label to the x axis
ylabel: Its label to the y-axis

How to create a Line graph in R?

Now let’s start our journey by creating a line graph step by step. Slowly and steadily it will give you a good grip over the line graph plotting with multiple tunings in it.

Popular Course in this category
R Programming Training (12 Courses, 20+ Projects)12 Online Courses | 20 Hands-on Projects | 116+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,998 ratings)
Course Price

View Course

Related Courses
Statistical Analysis Training (10 Courses, 5+ Projects)All in One Data Science Bundle (360+ Courses, 50+ projects)

Before plotting the line graph, one needs to know whether the function one going to use is available in the R environment or has to be installed.

The first function we will learn is plot() and another one would be ggplot. For plot(), one need not install any library. However, for ggplot, the library “ggplot2” needs to be installed and read that library like: “library(ggplot2)” in the R environment.

For installation in RStudio. Go to Tools -> Install packages

Line graph in R 2

1. Simple Line Graph in R code (with Plot function):

Vec <- c(7,12,28,3,41) #Create the data for the chart
plot(Vec,type = "o")  # Plot the bar chart.

Output:

Vector plot

Fig 2: Vector plot

Here you will notice x label, y label has not been assigned, so the default names as came.

Let’s say now R code is:

Vec <- c(7,12,28,3,41) #Create the data for the chart.
plot(Vec,type = "o",xlab = "Month", ylab = "Event Count", main = "Event Count by Month")

Output:

Vector plot with customized labels

Fig 3: Vector plot with customized labels

2. Saving Line graph in the PNG file.

The line graph drawn till now is in Rstudio pane. However, there come to the cases when you need to save it in the local system in the form of png files.

R code:

#Create the data for chart.
Vec <- c(17,12,22,30,4)
# Name on PNG image.
png(file = "First_chart.jpg")
# Plot the line chart.
plot(Vec,type = "o",xlab = "Month", ylab = "Event Count", main = "Event Count by Month")
# Save the file.
dev.off()

Here the png file will be saved in your current working directory, which you always check and change as per your requirement. Function: getwd() and setwd() can help you do so.

Line graph in R 5

See the location, and you will find “Line_chart.png” will be created.

Line graph in R 6

3. Multiple Lines in Line Chart

In a real-world scenario, there is always a comparison between various line charts. In order to plot multiple lines in a single line chart, below is the R code for that:

R Code:

events1 <- c(7,12,28,3,41)
events2 <- c(17,21,18,13,22)
# Plot the bar chart.
plot(events1,type = "o",col = "red", xlab = "Month", ylab = "Event Count",
main = "Event count chart")
lines(events2, type = "o", col = "blue")

Output:

Line graph in R 7

4. Add a legend to Line Graph

 We saw how to plot multiple lines in a single line chart. When there are more than two lines in the same line graph, it becomes clumsy to read. Legend plays a crucial factor there in order to understand plotted data in a lucid way.

R code:

events1 <- c(7,12,28,3,41)
events2 <- c(17,21,18,13,22)
# Plot the bar chart.
plot(events1,type = "o",col = "red", xlab = "Month", ylab = "Event Count",
main = "Event count chart")
lines(events2, type = "o", col = "blue")
# Add a legend
legend(3.5, 38, legend=c("Event 1", "Event 2"),
col=c("red", "blue"), lty=1:2, cex=0.8)

Output:

Line graph in R 8

The legend is usually placed on the top right-hand side corner. However, from a readability perspective, it could be placed as per one’s own comfortability. The first two parameters in the legend function show the x and y-axis where legend needs are placed.

If some doesn’t want to deal with coordinates, one specify legend position in terms of keywords like: “bottom”,”bottomright”, “bottomleft”, “left”, “topleft”, “top”, “right”, “topright” and “center”.

One can also customize legend, see below:

R Code:

events1 <- c(7,12,28,3,41)
events2 <- c(17,21,18,13,22)
# Plot the bar chart.
plot(events1,type = "o",col = "red", xlab = "Month", ylab = "Event Count",
main = "Event count chart")
lines(events2, type = "o", col = "blue")
# Add a legend
legend(3.5, 38, legend=c("Event 1", "Event 2"),
col=c("red", "blue"), lty=1:2, cex=0.8,
title="Event types", text.font=3, bg='lightblue')

Output:

Event count chart

Note: All the line graphs plotted above were through the function plot(). However, there are other libraries/functions also available which help us draw the line graph. One such library is “ggplot2”.

GGplot2 Library

below is the ggplot2 library which helps to draw line graph in R are as follows:

1. Simple Line Graph

R Code:

temp = c(4, 25, 50, 85, 100)
enzyme_activity = c(0.543, 0.788, 0.800, 0.898, 0.882)
df <- as.data.frame(cbind(temp,enzyme_activity))
library(ggplot2)
ggplot(df, aes(x = temp, y = enzyme_activity)) + geom_line()

Output:

Line graph in R 10

2. Multiple Lines in Line Graph

R Code:

library(ggplot2)
temp = c(4, 25, 50, 85, 100)
enzyme_one_activity = c(0.543, 0.788, 0.800, 0.898, 0.882)
enzyme_two_activity = c(0.702, 0.204, 0.400, 0.329, 0.443)
df <- as.data.frame(cbind(temp,enzyme_one_activity,enzyme_two_activity))
ggplot(df, aes(temp)) +
geom_line(aes(y = enzyme_one_activity),col ="red") +
geom_line(aes(y = enzyme_two_activity),col ="blue")

Output:

Line graph in R 11

3. More Details to Graph

 R Code:

library(ggplot2)
temp = c(4, 25, 50, 85, 100)
enzyme_one_activity = c(0.543, 0.788, 0.800, 0.898, 0.882)
enzyme_two_activity = c(0.702, 0.204, 0.400, 0.329, 0.443)
df <- as.data.frame(cbind(temp,enzyme_one_activity,enzyme_two_activity))
ggplot(df, aes(temp)) +
geom_line(aes(y = enzyme_one_activity),col ="red") +
geom_line(aes(y = enzyme_two_activity),col ="blue")+
labs(title = "Enzyme activity w.r.t Temperature", x = "Temperature(in Celsius)", y = "Enzyme Type")

Output:

Enzyme activity

Conclusion

A line graph is a basic yet very powerful chart to describe events over a certain time. R being a popular statistical tool, one must know how to plotline chart and how to customize its parameters to get the view as per one’s requirement. Once one gets comfortable with line graphs, other graphs should also be explored, to get a good grip over data visualization.

 Recommended Articles

This is a guide to Line Graph in R. Here we discuss what is line graph in R, The basic syntax to draw a line chart in R, etc. You can also go through our other suggested articles to learn more –

  1. Graphs vs Charts
  2. Excel Types of Graphs
  3. Scatterplots in R
  4. Guide to Binomial Distribution in R
  5. Guide to Plot Function in R

R Programming Training (12 Courses, 20+ Projects)

12 Online Courses

20 Hands-on Projects

116+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
R programming Tutorial
  • Chart/graphs
    • Graphs in R
    • Bar Charts in R
    • Pie Chart in R
    • Histogram in R
    • Line Graph in R
    • Plot Function in R
    • Scatterplot in R
    • R Boxplot labels
  • Basic
    • What is R Programming Language
    • Careers in R Programming
    • Install R
    • List of R Packages
    • Introduction of R Tools Technology
    • R Programming Language
    • What is RStudio?
    • R-studio-Functions
    • R Packages
    • R Data Types
    • R Operators
    • Vectors in R
  • Control statement
    • If Statement in R
    • If Else Statement in R
    • Else if in R
    • Switch Statement in R
  • Loops
    • Loops in R
    • For Loop in R
    • Nested For Loop in R
    • While Loop in R
    • Next in R
  • Regression in R
    • Simple Linear Regression in R
    • Linear Regression in R
    • Multiple Linear Regression in R
    • Logistic Regression in R
    • Poisson Regression in R
    • OLS Regression in R
    • P-Value in Regression
  • Anova in R
    • ANOVA in R
    • One Way ANOVA in R
    • Two Way ANOVA in R
  • Data Structure
    • R list
    • Arrays in R
    • Data Frames in R
    • Factors in R
  • Advanced
    • Statistical Analysis with R
    • R String Functions
    • Data Exploration in R
    • R CSV Files
    • KNN Algorithm in R
    • Sorting in R
    • lm Function in R
    • Hierarchical Clustering in R
    • R Normal Distribution
    • Binomial Distribution in R
    • Decision Tree in R
    • GLM in R
    • Linear Model in R
    • Predict Function in R
    • Survival Analysis in R
    • Standard Deviation in R
    • Statistical Analysis in R
    • T-test in R
    • Database in R
  • Programs
    • R Program Functions
    • Factorial in R
    • Random Number Generator in R
  • Interview question
    • R Interview Questions

Related Courses

R Programming Certification Course

Statistical Analysis Course Training

All in One Data Science Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - R Programming Training (12 Courses, 20+ Projects) Learn More