1.直方图
直方图和柱形图的区别:直方图表示频数,柱形图表示数量。
一般直方图的X轴表示取值范围,Y轴表示频数
hist() 函数
> hist(rnorm(1000)) #1000个正态随机数的直方图
> hist(islands) #岛屿数据集直方图
2.概率密度直方图
> air<-read.csv("airpollution.csv")
> hist(air$Nitrogen.Oxides,
+ freq=FALSE, #不显示频数,显示概率
+ xlab="Nitrogen Oxide Concentrations",
+ main="Distribution of Nitrogen Oxide Concentrations")
3.调整直方图范围密度
> hist(air$Nitrogen.Oxides,
+ breaks=20, #设置范围数
+ xlab="Nitrogen Oxide Concentrations",
+ main="Distribution of Nitrogen Oxide Concentrations")
> hist(air$Nitrogen.Oxides,
+ breaks=c(0,100,200,300,400,500,600), #指定范围
+ xlab="Nitrogen Oxide Concentrations",
+ main="Distribution of Nitrogen Oxide Concentrations")
4.直方图美化
①颜色美化
> hist(air$Respirable.Particles,
+ prob=TRUE, #纵坐标轴显示概率而不是频数
+ col="black",
+ border="white", xlab="Respirable Particle Concentrations",
+ main="Distribution of Respirable Particle Concentrations")
②线条美化
> par(yaxs="i",las=1)
> hist(air$Respirable.Particles, prob=TRUE,
+ col="black",border="white",
+ xlab="Respirable Particle Concentrations",
+ main="Distribution of Respirable Particle Concentrations")
> box(bty="l") #设置坐标轴样式
> grid(nx=NA,ny=NULL, #X轴没有线条,Y轴自动计算线条位置
+ lty=1,lwd=1,col="gray") #设置线条的样式、宽度和颜色
5.标识密度函数Density()函数
> par(yaxs="i",las=1)
> hist(air$Respirable.Particles,
+ prob=TRUE,col="black",border="white",
+ xlab="Respirable Particle Concentrations",
+ main="Distribution of Respirable Particle Concentrations")
+ box(bty="l")
> lines(density(air$Respirable.Particles,na.rm=T), #density()作密度函数
+ col="red",lwd=4)
> grid(nx=NA,ny=NULL,lty=1,lwd=1,col=" gray")
6.散点图+直方图
> panel.hist <- function(x, ...)
+ {
+ par(usr = c(par("usr")[1:2], 0, 1.5) )
+ hist(x,
+ prob=TRUE,
+ add=TRUE,col="bla ck",border="white")
+ }
> plot(iris[,1:4],
+ main="Relationships between characteristics of iris flowers",
+ pch=19,col="blue",cex=0.9,
+ diag.panel=panel.hist) #对角线画直方图
> layout(matrix(c(2,0,1,3),2,2,byrow=TRUE),
+ widths=c(3,1), heights=c(1,3), TRUE)
> par(mar=c(5.1,4.1,0.1,0)) #画散点图
> plot(air$Respirable.Particles~air$Nitrogen.Oxides, pch=19,col="black", xlim=c(0,600),ylim=c(0,80),
+ xlab="Nitrogen Oxides Concentrations",
+ ylab="Respirable Particle Concentrations")
> par(mar=c(0,4.1,3,0)) #画上方的直方图
> hist(air$Nitrogen.Oxides, breaks=seq(0,600,100),
+ ann=FALSE,axes=FALSE, #无注释,无坐标轴
+ col="black",border="white")
> yhist <- hist(air$Respirable.Particles,
+ breaks=seq(0,80,10),plot=FALSE)
> par(mar=c(5.1,0,0.1,1)) #画右边的直方图
> barplot(yhist$density, horiz=TRUE,
+ space=0,axes=FALSE,
+ col="black",border="white")