@[toc]
自己构造两份简单的文件
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变为每块区域的占比,可以使用如下一种较巧妙的形式,重点在于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')
直方图
默认绘图
data = read.csv(file=file.choose(),header = T)
attach(data)
hist(age)
增加颜色,标签
hist(weight,labels = T,col = c("red","pink","yellow","blue"),main = "histogram of weight")
箱型图
boxplot(data$age, main = "age boxplot", ylab = "age")
中间的箱型表示1/4分位数和3/4分位数,中间的粗黑线表示中位数
散点图
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)
散点图,按照职业分类,并绘制回归线
ggplot(data,aes(x = age, y = height, col = career)) + geom_point() + geom_smooth(method = lm)
网友评论