Data Visualisation: Plot Two Continuous Variables Using GGPLOT2 | R Programming

Objective: Plot two variables using ggplot2 where both the variables are continuous series. 

A variable is said to be continuous if it has an infinite number possible values and is not limited by any condition. For example age, weight or height of person can have any possible value. 
It is very important to learn how to visualise continuous variable for exploratory analysis and data visualisation.  

Step 1: Install and load required packages

>install.packages("ggplot2")
>library(ggplot2)
>library(datasets)

Load Dataset
>data("iris")

Step 2: Plot Sepal.Length and Sepal.Width using ggplot2

Basic Jitter plot
>ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width))+geom_jitter()

Output:



Plot points and include more details. change the shape of the dots and make them represent another variable i.e. Species

>ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width))+geom_point(alpha = 0.9, color = c("dark red"), shape = iris$Species, size  = 3)

Output:
 

Turn your graph into a 2D with density by adding contour

>ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width))+stat_density2d(contour = TRUE, n = 100)


Add a smooth plot aka smoothened conditional means which aids in seeing patterns in presence of overplotting. 

>ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width))+stat_smooth(method = "loess", formula = y ~ x, se = TRUE, n = 100, fullrange = FALSE, level = 0.95)

Output:



Instagram Post You May Like