Plotting using ggplot2
First, we need to install the library using following command
install.packages("ggplot2")
- ggplot is a popular data visualization package in R programming.
Then we can use it as usual by importing the library into script.
R
# Importing library library (ggplot2) # Reading Dataset SalaryData <- read.csv ( "placement.csv" ) # Preparing model model <- lm (package ~ cgpa, data = SalaryData) png (file = "placement_stats.png" ) ggplot (SalaryData, aes (x = cgpa, y = package)) + geom_point () + # For displaying points geom_smooth (method = "lm" , se = FALSE ) + # for displaying line labs (title = "CGPA and Package regression" , x = "CGPA" , y = "Y" ) |
Output:
It works in similar manner as previous one, both line of best fit and points are plotted on the graph
Without geom_point (plotting points absent)
R
# Importing library library (ggplot2) # Reading Dataset SalaryData <- read.csv ( "placement.csv" ) # Preparing model model <- lm (package ~ cgpa, data = SalaryData) png (file = "placement_stats.png" ) ggplot (SalaryData, aes (x = cgpa, y = package)) + geom_smooth (method = "lm" , se = FALSE ) + # geom_points removed labs (title = "CGPA and Package regression" , x = "CGPA" , y = "Y" ) |
Output:
When removing geom_point parameter the plotting points are not displayed on the graph while keeping everything same.
Without geom_smooth (line absent)
R
# Importing library library (ggplot2) # Reading Dataset SalaryData <- read.csv ( "placement.csv" ) # Preparing model model <- lm (package ~ cgpa, data = SalaryData) png (file = "placement_stats.png" ) ggplot (SalaryData, aes (x = cgpa, y = package)) + geom_point ()+ labs (title = "CGPA and Package regression" , x = "CGPA" , y = "Y" ) |
Output:
When removing geom_smooth parameter the line of best fit is not displayed on the graph while keeping everything same.
How to Plot the Linear Regression in R
In this article, we are going to learn to plot linear regression in R. But, to plot Linear regression, we first need to understand what exactly is linear regression.
Contact Us