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文章來源地址http://www.zghlxwxcb.cn/news/detail-533221.html
文章來源:http://www.zghlxwxcb.cn/news/detail-533221.html
到了這里,關于R語言學習——散點圖和折線圖的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!