@[toc]
自己構(gòu)造兩份簡單的文件
test1.csv
career,age,height,weight
doctor,32,170,110
director,24,164,99
teacher,43,156,110
actor,22,177,93
cook,44,166,140
test2.csv
career,gender,age,height,weight
doctor,f,32,170,110
doctor,f,26,165,105
doctor,f,34,155,122
doctor,f,22,154,130
doctor,f,36,166,112
doctor,m,44,185,100
doctor,m,38,165,110
doctor,m,33,170,145
doctor,m,40,177,134
doctor,m,41,170,155
director,f,24,164,99
director,f,25,164,121
director,f,26,174,105
director,f,31,160,101
director,f,32,164,102
director,m,33,155,110
director,m,22,164,143
director,m,45,178,142
director,m,32,183,133
director,m,47,164,123
teacher,f,43,156,110
teacher,f,33,155,123
teacher,f,43,167,92
teacher,f,54,164,143
teacher,f,34,162,122
teacher,m,21,164,105
teacher,m,43,177,123
teacher,m,33,173,155
teacher,m,43,164,162
teacher,m,33,180,124
柱狀圖
#自動指定顏色
data <- read.csv(file = 'test1.csv',header = TRUE)
barplot(data$age,names.arg = data$career,main = "age graph", xlab = "career", ylab ="age",col = rainbow(length(data$age)))
#增加圖例
barplot(data$age,names.arg = data$career,main = "age graph", xlab = "career", ylab ="age",col = rainbow(length(data$age)),legend.text = c('doctor','director','teacher','actor','cook'))
餅圖
pie(data$height,data$career,main='height of different career',radius=1, col = rainbow(length(data$height)))
如果想使label變?yōu)槊繅K區(qū)域的占比,可以使用如下一種較巧妙的形式,重點在于piepercent
piepercent<- paste(round(100*data$height/sum(data$height), 2), "%")
pie(data$height,labels = piepercent,main='height of different career',radius=1, col = rainbow(length(data$height)))
legend("topright", c("doctor","director","teacher","actor","cook"), cex = 0.7, fill = rainbow(length(data$height)))
3D餅圖
library("plotrix")
pie3D(age,labels=c('doctor','director','teacher','actor','cook'),explode=0.1,main='3D pie graph')
直方圖
默認(rèn)繪圖
data = read.csv(file=file.choose(),header = T)
attach(data)
hist(age)
增加顏色,標(biāo)簽
hist(weight,labels = T,col = c("red","pink","yellow","blue"),main = "histogram of weight")
箱型圖
boxplot(data$age, main = "age boxplot", ylab = "age")
中間的箱型表示1/4分位數(shù)和3/4分位數(shù),中間的粗黑線表示中位數(shù)
散點圖
plot(age,height,col='red',pch=20)
abline(lm(height~age),col='blue')
使用ggplot2
餅圖
library(ggplot2)
attach(data)
df <- data.frame(type=career,nums = age)
bp <- ggplot(data = df, mapping = aes(x='content', y=nums, fill=career))+
geom_bar(width = 1, stat = "identity")
pie <- bp + coord_polar(theta = 'y')
pie
散點圖,增加回歸線
library(ggplot2)
ggplot(data,aes(x = age, y = height)) + geom_point()
ggplot(data,aes(x = age, y = height)) + geom_point() + geom_smooth(method = lm)
散點圖,按照性別分類,并繪制回歸線
ggplot(data,aes(x = age, y = height, col = gender)) + geom_point() + geom_smooth(method = lm)
散點圖,按照職業(yè)分類,并繪制回歸線
ggplot(data,aes(x = age, y = height, col = career)) + geom_point() + geom_smooth(method = lm)