Plot using ggplot2 graphics in R Programming Language

Rumman Ansari   Software Engineer   2023-03-24   5859 Share
☰ Table of Contents

Table of Content:


For both histogram and density plot is very much useful for single varivable. Before woring on plot please see related data on which we are going to working.

# Installation 

install.packages("ggplot2")
require(ggplot2)
data(diamonds)

class(diamonds)

# understand the diamonds data set
help(diamonds)

# see first 6 rows how its looks like

head(diamonds)

Plot histograms and densities with ggplot2

  
ggplot(data = diamonds) + geom_histogram( aes(x = carat) ) 

ggplot(data = diamonds) + geom_histogram( aes(x = carat), binwidth = .1 ) 

ggplot(data = diamonds) + geom_histogram( aes(x = carat), binwidth = .1 )  

densities plot

  
ggplot(data = diamonds) + geom_density(aes(x = carat))

ggplot(data = diamonds) + geom_density(aes(x = carat), fill= "grey50")

Make scatterplots with ggplot2

  
ggplot(diamonds, aes(x = carat, y = price)) + geom_point()

You can do that above this in much flexiable manner like below for code reuseability

g <-  ggplot(diamonds, aes(x = carat, y = price))

g + geom_point()

Color code the plot according to the color of the diamonds

  
g + geom_point(aes(color=color))  

g + geom_point(aes(color=color, shape = cut))
  

You can see clearly the plot using Zoom

Make boxplots and violin plots with ggplot2

Box plot does not x axis

  g <- ggplot(diamonds, aes(y = carat, x =1))
  g + geom_boxplot()

Based on labels

  g <- ggplot(diamonds, aes(y = carat, x =cut))
  g + geom_boxplot()

violin plots

  g <- ggplot(diamonds, aes(y = carat, x =cut))
  g + geom_violin()

Layer Overlaping

  g <- ggplot(diamonds, aes(y = carat, x =cut))
  g + geom_point()  + geom_violin() 

Change the oreder of layers

  g <- ggplot(diamonds, aes(y = carat, x =cut))
  g + geom_violin()  + geom_point()

Using geom_jitter

  g <- ggplot(diamonds, aes(y = carat, x =cut))
  g + geom_jitter() + geom_violin()