頻率直方圖是數(shù)據(jù)統(tǒng)計中經(jīng)常會用到的圖形展示方式,同時在生物學(xué)分析中可以更好的展示表型性狀的數(shù)據(jù)分布類型;R基礎(chǔ)做圖中的hist函數(shù)對單一數(shù)據(jù)的展示很方便历造,但是當(dāng)遇到多組數(shù)據(jù)的時候就不如ggplot2繪制來的方便互妓。
1.基礎(chǔ)做圖hist函數(shù)
hist(rnorm(200),col='blue',border='yellow',main='',xlab='')
1.1 多圖展示
par(mfrow=c(2,3))
for (i in 1:6) {hist(rnorm(200),border='yellow',col='blue',main='',xlab='')}
2.ggplot2繪制
- 構(gòu)造一組正態(tài)分布的數(shù)據(jù)
PH<-data.frame(rnorm(300,75,5))
names(PH)<-c('PH')
#顯示數(shù)據(jù)
head(PH)
## PH
## 1 72.64837
## 2 67.10888
## 3 89.34927
## 4 75.70969
## 6 82.85354
- 加載ggplot2作圖包并繪圖
library(ggplot2)
library(gridExtra)
p1<-ggplot(data=PH,aes(PH))+
geom_histogram(color='white',fill='gray60')+ #控制顏色
ylab(label = 'total number') #修改Y軸標(biāo)簽
2.1 修改柱子之間的距離
p2<-ggplot(data=PH,aes(PH))+
geom_histogram(color='white',fill='gray60',binwidth = 3)
2.2 添加擬合曲線
p3<-ggplot(data=PH,aes(PH,..density..))+
geom_histogram(color='white',fill='gray60',binwidth = 3)+
geom_line(stat='density')
2.3 修改線條的粗細(xì)
p4<-ggplot(data=PH,aes(PH,..density..))+
geom_histogram(color='white',fill='gray60',binwidth = 3)+
geom_line(stat='density',size=1.5)
grid.arrange(p1,p2,p3,p4)
2.4 繪制密度曲線
p1<-ggplot(data=PH,aes(PH,..density..))+
geom_density(size=1.5)
2.5 修改線條樣式
p2<-ggplot(data=PH,aes(PH,..density..))+
geom_density(size=1.5,linetype=2)
p3<-ggplot(data=PH,aes(PH,..density..))+
geom_density(size=1.5,linetype=5)
2.6 修改顏色
p4<-ggplot(data=PH,aes(PH,..density..))+
geom_density(size=1.5,linetype=2,colour='red')
grid.arrange(p1,p2,p3,p4)
2.7 多組數(shù)據(jù)展示
- 構(gòu)造兩組數(shù)據(jù)
df<-data.frame(c(rnorm(200,5000,200),rnorm(200,5000,600)),rep(c('BJ','TJ'),each=200))
names(df)<-c('salary','city')
- 結(jié)果展示
library(ggplot2)
p1<-ggplot()+
geom_histogram(data=df,aes(salary,..density..,fill=city),color='white')
p2<-ggplot()+
geom_histogram(data=df,aes(salary,..density..,fill=city),color='white',alpha=.5)
p3<-ggplot()+
geom_density(data=df,aes(salary,..density..,color=city))
p4<-ggplot()+
geom_histogram(data=df,aes(salary,..density..,fill=city),color='white')+geom_density(data=df,aes(salary,..density..,color=city))
grid.arrange(p1,p2,p3,p4)