a <- read.table('/Users/zhangzhishuai/Downloads/24 lesson24 R主成分分析/24_pca/BMI.txt', header = T,sep = '\t', row.names = 1)
a
# 散点图
plot(a$weight, a$height, # 读xytype = 'p', # 代表画的是点,l代表直线,b既有点又有线,n代表空main = 'weight vs height',xlab = 'weight', # x轴标签ylab = 'height', # y轴标签ylim = c(160,180), # y范围xlim = c(55,75), # x轴范围col = 'red', # 颜色pch = 19 # 形状
)index = order(a$weight,decreasing = F) # 对x轴排序获取索引
data=a[index,]
# 折线图
plot(data$weight, data$height, # 读xytype = 'l', # 代表画的是点,l代表直线,b既有点又有线main = 'weight vs height',xlab = 'weight', # x轴标签ylab = 'height', # y轴标签ylim = c(160,180), # y范围xlim = c(55,75), # x轴范围col = 'red', # 颜色pch = 19 # 形状
)# 线和点都有
plot(data$weight, data$height, # 读xytype = 'b', # 代表画的是点,l代表直线,b既有点又有线main = 'weight vs height',xlab = 'weight', # x轴标签ylab = 'height', # y轴标签ylim = c(160,180), # y范围xlim = c(55,75), # x轴范围col = 'red', # 颜色pch = 19 # 形状
)# 加折线
male = data[data$gender=='male',]
female = data[data$gender=='female',]
plot(female$weight,female$height,type = 'b',main = 'weight vs height',xlab = 'weight', # x轴标签ylab = 'height', # y轴标签ylim = c(160,180), # y范围xlim = c(55,75), # x轴范围col = 'red', # 颜色pch = 19 # 形状
)
lines(male$weight,male$height,col='blue',type = 'b') # 在图上加线# 制定颜色和形状,分组
color = ifelse(data$gender=='male','blue','red')
shape = ifelse(data$gender=='male',19,21)
plot(data$weight, data$height,type = 'b',main = 'weight vs height',xlab = 'weight', # x轴标签ylab = 'height', # y轴标签ylim = c(160,180), # y范围xlim = c(55,75), # x轴范围col = color,pch = shape
)
legend('topleft',legend = c('male','female'),col = c('blue','red'),pch = c(19,21))
# 图上加文字
text(58, #文字的横坐标166, # 文字的纵坐标'Cindy')
# 图上加直线
abline(v=65, # v指画垂直线,横坐标为65col='red',lty = 3, # 控制线类型lwd=3 # 控制线宽度
)
abline(h=170, # h代表水平线col = 'green',lty=4,lwd=2
)
# 图上加线性拟合直线
result = lm(height~weight, data)
summary(result)
abline(result,col='black')
text(60,178,'pvalue=0.0122\nR-squared=0.7815')# 图片保存
pdf(file='/Users/zhangzhishuai/Downloads/24 lesson24 R主成分分析/24_pca/scatter_line2.pdf',width = 10, # 宽度height = 7 # 高度)
dev.off() # 关掉pdf,一定要关掉
BMI.txt
name height weight gender BMI
tom 180 75 male 23.1481481481481
cindy 165 58 female 21.3039485766759
jimmy 175 72 male 23.5102040816327
sam 173 68 male 22.7204383708109
lucy 160 60 female 23.4375
lily 165 55 female 20.2020202020202