R语言ggplot2——折线图

BMI <- read.table('/Users/zhangzhishuai/Downloads/33 lesson33 ggplot2散点图(一)/33_ggplot2/BMI.txt', header = T,sep = '\t', row.names = 1)
library(ggplot2)
ggplot(BMI, aes(x=weight,y=height)) +
  geom_line() # 折线图

# 加文字
ggplot(BMI, aes(x=weight,y=height)) +
  geom_line() +
  geom_text(label = rownames(BMI)) #加名字(用行名)

# 设置文字颜色
ggplot(BMI, aes(x=weight,y=height)) +
  geom_line() + 
  geom_text(label = rownames(BMI), colour = BMI$age) # 根据年龄标注颜色
  
ggplot(BMI, aes(x=weight,y=height)) +
  geom_line() + 
  geom_text(label = rownames(BMI), aes(colour = age)) + # 根据年龄标注颜色(将年龄放入aes中)
  scale_colour_gradient(low = 'yellow', high = 'red') # 改变图注渐变色

# 使用geom_label加文字,会在文字周围加一个边框,其他和geom_text一样
ggplot(BMI, aes(x=weight,y=height)) +
  geom_line() + 
  geom_label(label = rownames(BMI), aes(colour = age)) + # 根据年龄标注颜色(将年龄放入aes中)
  scale_colour_gradient(low = 'yellow', high = 'red') # 改变图注渐变色

# 改变线的属性和点的属性
ggplot(BMI, aes(x=weight,y=height)) +
  geom_line(colour = 'red', linetype=2 #控制线类型相当于lty
            , size=2 # 控制线粗细相当于lwd
            ) +
  geom_point(size = 8, shape = 20) # 控制点的大小和形状

# 根据连续变量改变点的颜色
ggplot(BMI, aes(x=weight,y=height)) +
  geom_line(colour = 'red', linetype=2, size=2) +
  geom_point(size = 8, shape = 20, aes(color = age) # 连续变量控制颜色
             ) + 
  scale_colour_gradient(low = 'yellow', high = 'red') 

# 分组划折线
ggplot(BMI, aes(x=weight,y=height, group = gender)) +
  geom_line(aes(color = gender, linetype = gender), size = 1) + # 改变线的分组颜色
  geom_point(aes(color = gender, shape = gender), size = 3) # 改变点的分组颜色

# 划多条折线
BMI$name = rownames(BMI)
ggplot(BMI,aes(x=1:6,y=height)) +
  geom_line(color='red',linetype=1) +
  geom_point(color = 'red') +
  geom_line(aes(x=1:6,y=weight),linetype=2,size=2) +
  geom_point(aes(x=1:6,y=weight),size=2)

ggplot(BMI,aes(x=name,group=1)) +
  geom_line(aes(y=weight),color='red',linetype=1) +
  geom_line(aes(y=height),color='steelblue',linetype='twodash') +
  geom_line(aes(y=age),color='green',linetype='dashed') + 
  geom_line(aes(y=BMI),color='purple',linetype='dotdash')

# 一次性划多条折线
library('reshape2')
library('ggplot2')
bmi = melt(BMI[,-3],id='name')  
ggplot(bmi,aes(x=name,y=value,group=variable,linetype=variable,color = variable)) +
  geom_line(size=1) + 
  geom_point(aes(shape=variable,color=variable),size=2)

# 保存图片
ggsave(file = '/Users/zhangzhishuai/Downloads/33 lesson33 ggplot2散点图(一)/33_ggplot2/line.pdf',width = 7,height = 9)

示例文件BMI.txt:

name	height	weight	gender	BMI	age
tom	180	75	male	23.14814815	38
cindy	165	58	female	21.30394858	45
jimmy	175	72	male	23.51020408	43
sam	173	68	male	22.72043837	35
lucy	160	60	female	23.4375	32
lily	163	55	female	20.2020202	28

你可能感兴趣的:(R语言学习,r语言,开发语言)