R語言繪制頻率直方圖的案例
頻率直方圖是數(shù)據(jù)統(tǒng)計中經(jīng)常會用到的圖形展示方式,同時在生物學分析中可以更好的展示表型性狀的數(shù)據(jù)分布類型;R基礎做圖中的hist函數(shù)對單一數(shù)據(jù)的展示很方便,但是當遇到多組數(shù)據(jù)的時候就不如ggplot2繪制來的方便。
***
1.基礎做圖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軸標簽
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 修改線條的粗細
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)

補充:R語言在直方圖上添加正太曲線與核密度曲線
lines(x=橫坐標向量,y=縱坐標向量),在已有圖像上添加曲線
hist(數(shù)值型向量,freq=TRUE/FALSE)freq取TRUE縱坐標為頻數(shù),否則為頻率



以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章
詳解R語言MCMC:Metropolis-Hastings采樣用于回歸的貝葉斯估計
這篇文章主要介紹了R語言MCMC:Metropolis-Hastings采樣用于回歸的貝葉斯估計,本文通過圖文實例相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03
R語言rhdf5讀寫hdf5并展示文件組織結(jié)構(gòu)和索引數(shù)據(jù)
這篇文章主要為大家介紹了R語言rhdf5讀寫hdf5并展示文件組織結(jié)構(gòu)和索引數(shù)據(jù),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06

