0
点赞
收藏
分享

微信扫一扫

R语言学习——散点图和折线图

前程有光 2023-07-13 阅读 81
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, # 读xy
  type = '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, # 读xy
  type = '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, # 读xy
  type = '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指画垂直线,横坐标为65
  col='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

举报

相关推荐

0 条评论