R語言繪制頻率直方圖的案例
頻率直方圖是數(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)
補(bǔ)充:R語言在直方圖上添加正太曲線與核密度曲線
lines(x=橫坐標(biāo)向量,y=縱坐標(biāo)向量),在已有圖像上添加曲線
hist(數(shù)值型向量,freq=TRUE/FALSE)freq取TRUE縱坐標(biāo)為頻數(shù),否則為頻率
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
R語言 數(shù)據(jù)表匹配和拼接 merge函數(shù)的使用
這篇文章主要介紹了R語言 數(shù)據(jù)表匹配和拼接 merge函數(shù)的使用說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03R語言中的vector(向量),array(數(shù)組)使用總結(jié)
這篇文章主要介紹了R語言中的vector(向量),array(數(shù)組)使用總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03R語言數(shù)據(jù)類型轉(zhuǎn)換的實現(xiàn)(向量,列表,矩陣)
我們在使用R語言做數(shù)據(jù)分析時,會一直對數(shù)據(jù)進(jìn)行不同類型的轉(zhuǎn)換,本文主要介紹了R語言數(shù)據(jù)類型轉(zhuǎn)換的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2024-04-04