[TOC]
ggplot2 学习笔记
1.安装
install.packages('ggplot2')
2.qplot
set.seed(1410)##让样本可重复
dsmall<-diamonds[sample(nrow(diamonds),100),]#取前100行
head(dsmall,4)
qplot(carat,price,data=diamonds)
> head(diamonds,4)
carat cut color clarity depth table price x y z
1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43
2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31
3 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31
4 0.29 Premium I VS2 62.4 58 334 4.20 4.23 2.63

qplot(carat,price,data=dsmall,colour=color,shape=cut)

qplot(log(carat),log(price),data=diamonds,alpha=I(1/100))
# I()手动设定图形属性,如color=I('red');alpha设定透明度,0为完全透明

#geom="point",散点图
#geom="smooth",拟合平滑曲线
#geom="boxplot",箱线图
#geom="path"和geom="line",可在数据点之间绘制连线
#geom="histogram",直方图
#geom="freqploy",多边形
#geom="density",密度曲线
#geom="bar",条形图
qplot(carat,price,data=dsmall,geom=c("point","smooth")) # 若不想绘制标准误差,se=FALSE

qplot(color,price/carat,data=diamonds,geom="jitter",alpha=I(1/5)) #扰动点图

qplot(carat,data=diamonds,geom="histogram",binwidth=0.05,xlim=c(0,4),fill=color)

qplot(carat,data=diamonds,geom="density",xlim=c(0,4),color=color)

qplot(cut,price,data=diamonds,geom="boxplot",fill=cut)

2.1分面
#row_var ~ col_var;row_var ~ .会创建一个单列多行的图形矩阵
qplot(carat,data=diamonds,facets=color ~ .,geom="histogram",binwidth=0.1,xlim=c(0,3))

2.2选项
# xlim,ylim: x轴和y轴范围,xlim=c(0,20)
# log: log='x',表示x轴取对数
# main:图形主标题
# xlab,ylab: x,y轴标签文字
# 建立图形
p<-qplot(....)
# 保存图形对象
save(p,file="plot.rdata")
# 读入图形对象
load("plot.rdata")
# 将图片保存成png格式
ggsave("plot.png",width=5,height=5)
2.3甲基化的部分图
v=''
v$a=c(10,20,40,60,70)
v$b=c(-0.01,-0.02,-0.01,-0.02,-0.01)
v$d=c('Upstream','TSS','Genebody','TTS','Downstream')
v<-data.frame(v)
sort<-df[240]
sort<-sort(sort)
sort[240]
library('ggplot2')
df<-read.table('element.final',header=TRUE)
svg('TSS.svg')
ggplot(data=df)+geom_line(aes(x=pos,y=value/sort[240],color=type))+
ylab('normalized methylation level')+geom_text(data=v,aes(x=a,y=b,label=d),size=3,color=I('red'))+
xlab('')
dev.off()

setwd('/lustre/project/og04/shichunwei/project/bisulfite_sequencing/mouse/out/SRR1040649/test')
df<-read.table("NC_000084.6.txt",header=TRUE)
library('ggplot2')
qplot(count,value,data=df,geom="line",color=color,facets=type~.,alpha=I(8/10))+theme(legend.position='none')+
xlab('')+ylab('')

2.4 其他选项
library('ggplot2')
p<-qplot(cyl,wt,data=mtcars)
p+scale_x_continuous(breaks=c(5.5,6.5)) # breaks 横坐标只显示5.5,6.5
p+scale_x_continuous(limits=c(5.5,6.5)) # limits 只显示5.5~6.5范围
p<-qplot(wt,cyl,data=mtcars,color=cyl)
p+scale_color_gradient(breaks=c(5.5,6.5)) # 与上面的类似,只是作用范围不是横坐标而是图注
p+scale_color_gradient(limits=c(5.5,6.5)) #
scale_x_log10() # x 轴转换成log10
#图例
theme(legend.position=right,left,top,bottom,none) # 控制图例位置

pie<-ggplot(mtcars,aes(x=factor(1),fill=factor(cyl)))+geom_bar(width=1)
pie + coord_polar(theta='y')+theme_bw()+xlab('')+ylab('')+labs(fill='')+
theme(axis.text = element_blank())+theme(axis.ticks = element_blank())
# theme_bw() 更改主题背景,改为白色

网友评论