溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

R語言如何繪制頻率直方圖

發(fā)布時(shí)間:2021-03-16 09:05:22 來源:億速云 閱讀:946 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)R語言如何繪制頻率直方圖,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

1.基礎(chǔ)做圖hist函數(shù)

hist(rnorm(200),col='blue',border='yellow',main='',xlab='')

R語言如何繪制頻率直方圖

1.1 多圖展示

par(mfrow=c(2,3))
for (i in 1:6) {hist(rnorm(200),border='yellow',col='blue',main='',xlab='')}

R語言如何繪制頻率直方圖

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)

R語言如何繪制頻率直方圖

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)

R語言如何繪制頻率直方圖

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語言如何繪制頻率直方圖

補(bǔ)充:R語言在直方圖上添加正太曲線與核密度曲線

lines(x=橫坐標(biāo)向量,y=縱坐標(biāo)向量),在已有圖像上添加曲線

hist(數(shù)值型向量,freq=TRUE/FALSE)freq取TRUE縱坐標(biāo)為頻數(shù),否則為頻率

R語言如何繪制頻率直方圖

R語言如何繪制頻率直方圖

R語言如何繪制頻率直方圖

關(guān)于“R語言如何繪制頻率直方圖”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI