原始数据:以position为横坐标,对一组和二组分别做折线
代码如下
library('ggplot2')
getwd()
workdir="C:/Users/lyqro/Desktop"
file="C:/Users/lyqro/Desktop/final_data.csv"
setwd(workdir)
dat=read.table(file,sep=",",check.names=F,header=T)
head(dat,10)
关键:两个折线图叠加
p_line=ggplot(dat)+
geom_line(aes(x=dat[,1],y=dat[,2]),color="red")+
geom_line(aes(x=dat[,1],y=dat[,3]),color="blue")
p_line
散点图同上:两个点图叠加即可
p_point=ggplot(dat)+
geom_point(aes(x=dat[,1],y=dat[,2]),color="red")+
geom_point(aes(x=dat[,1],y=dat[,3]),color="blue")
p_point
p_point=ggplot(dat)+
geom_line(aes(x=dat[,1],y=dat[,2]),color="red")+
geom_point(aes(x=dat[,1],y=dat[,2]),color="blue")
p_point
若要用显示不同分组,可先将“宽型数据”转化为“长型数据”,然后利用颜色对变量进行分组绘图
#1.宽型数据转化为长型数据
library(reshape2)
dat1=melt(dat, id.vars = c("Position"))
dat1
#以一二组为不同颜色组——进而绘制不同组折线图,关键代码:color=dat1[,2])
p_line=ggplot(dat1)+
geom_line(aes(x=dat1[,1],y=dat1[,3],color=dat1[,2]),size=1.2)+
scale_color_manual(values = c("blue","red"))+
#坐标间距调整
scale_x_continuous(breaks = seq(0, max(dat[,1])+5000, 5000))+
scale_y_continuous(breaks = seq(-1, 1, 0.1))+
#标注坐标名称、legend图例名称
labs(x="Gene position",y="Similarity",color="Group")+
#改图片其他参数
theme(
legend.title = element_text(size = 15,face = "bold"),
legend.text = element_text(size = 15, face = "bold"),
legend.position = 'right',
legend.key.size=unit(0.5,'cm'),
#axis.ticks.x=element_blank(),
axis.text.x=element_text(size = 15,face = "bold", vjust = 0.5, hjust = 0.5),
axis.text.y=element_text(size = 15,face = "bold", vjust = 0.5, hjust = 0.5),
axis.title.x = element_text(size = 15,face = "bold", vjust = -0.5, hjust = 0.5),
axis.title.y = element_text(size = 15,face = "bold", vjust = 1.2, hjust = 0.5),
panel.background = element_rect(fill = "transparent",colour = "black"),
# panel.grid.minor = element_line(color="lightgrey",size=0.1),
# panel.grid.major = element_line(color="lightgrey",size=0.1),
plot.background = element_rect(fill = "transparent",colour = "white")) ##colour = "black"是挡住横坐标字体的原因
p_line