This lesson is being piloted (Beta version)

Histogram plot

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • What is Histogram plot

Objectives
  • Learn how to plot histogram using ggplot2

Histogram

g <- ggplot(mpg, aes(displ)) + scale_fill_brewer(palette = "Spectral")
g + geom_histogram(aes(fill=class), 
                   bins=10, 
                   col="black", 
                   size=.1) +   # change number of bins
  labs(title="Histogram with Fixed Bins", 
       subtitle="Engine Displacement across Vehicle Classes",
       x="enginer displacement (m)",
       y="Frequency count") 

image

Density

g <- ggplot(mpg, aes(cty))
g + geom_density(aes(fill=factor(cyl)), alpha=0.8) + 
    labs(title="Density plot", 
         subtitle="City Mileage Grouped by Number of cylinders",
         caption="Source: mpg",
         x="City Mileage",
         fill="# Cylinders")+
    theme_bw()

image

Density 2D

gg <- ggplot(faithful,aes(x=eruptions,y=waiting))
gg + stat_density_2d(aes(fill=..level..),
                     geom="polygon",color="black")+
     geom_smooth(method="lm",linetype=2,color="red")+
     scale_fill_continuous(low="green",high="red")+
     geom_point() +
     theme_bw()

image

Key Points

  • histogram