Chapter 5 Default Histogram and Density Plots in R
A Histogram is NOT a Bar Chart:
Preference:https://www.edrawsoft.com/histogram-vs-bar-chart.php
Simple Histograms:
x: a numeric vector
breaks: breakpoints between histogram cells.
# Simple Histogram
par(mfrow=c(2,1), mar=c(3,3,1,0)+.5, mgp=c(1.6,.6,0))
hist(mtcars$mpg,col="mistyrose")
hist(mtcars$mpg, breaks =30,col="pink")
Colored Histogram:
hist(mtcars$mpg, breaks=12, col="mistyrose")
Add a Normal Curve:
x <- mtcars$mpg
h<-hist(x, breaks=10, col="mistyrose", xlab="Miles Per Gallon",
main="Histogram with Normal Curve")
xfit<-seq(min(x),max(x),length=40)
yfit<-dnorm(xfit,mean=mean(x),sd=sd(x))
yfit <- yfit*diff(h$mids[1:2])*length(x)
lines(xfit, yfit, col="red", lwd=2)
Density plots: density():
# The density data
dens <- density(mtcars$mpg)
# plot density
plot(dens, frame = FALSE, col = "red",
main = "Density plot of mpg")
Density plot using polygon():
plot(dens, frame = FALSE, col = "lightblue",
main = "Density plot of mpg")
polygon(dens, col = "#70E500")
Additional->Comparing density Plots:
Example-1:
#install.packages("sm")
library(sm)
## Package 'sm', version 2.2-5.6: type help(sm) for summary information
sm.density.compare(iris$Sepal.Length, iris$Species, xlab="Species")
title(main="Distributions of Species")
Example-2:
x <- seq(from = 110, to = 174, by = 0.5)
y1 <- dnorm(x, mean = 145, sd = 9)
y2 <- dnorm(x, mean = 138, sd = 8)
plot(x, y1, type="l", lwd=2, col="mistyrose",
main="Systolic Blood Pressure Before and After Treatment",
xlab = "Systolic Blood Pressure (mmHg)",
ylab = "Frequency", yaxt="n",
xlim = c(110, 175), ylim = c(0, 0.05))
lines(x, y2)
polygon(c(110,x,175),c(0,y2,0), col="green",
border = "orange")
polygon(c(117,x,175),c(0,y1,0), col="lightblue",
border = "orange")
ylab=c(seq(from=0, to=175, by=25))
y=c(seq(from=0, to=0.05, length.out = 8))
axis(2,at=y,labels=ylab, las=1)
text(x = 120, y = 0.045, "- Pre-Treatment BP", col = "#0E51A7", cex = 0.9)
text(x = 120, y = 0.04, " - Post-Treatment BP", col = "firebrick3", cex = 0.9)
points(109, 0.0445, pch = 15, col = "lightblue")
points(109, 0.0395, pch = 15, col = "lightblue")