本节讲的是如何多元化展示图片。
代码
1. 数据导入及整理
这一部分依旧是之前的内容,不做过多的解释
library(ggplot2)
# reset theme
theme_set(theme_gray())
# Loading the data
filename <- "Lesson-07/variants_from_assembly.bed"
my_data <- read.csv(filename, sep="\t", quote='', stringsAsFactors=TRUE,header=FALSE)
names(my_data) <- c("chrom","start","stop","name","size","strand","type","ref.dist","query.dist")
head(my_data)
# Filtering and polishing data
my_data <- my_data[my_data$chrom %in% c(seq(1,22),"X","Y","MT"),]
# ordering chromosomes
my_data$chrom <- factor(gsub("chr", "", my_data$chrom), levels=c(seq(1,22),"X","Y","MT"))
# ordering types
my_data$type <- factor(my_data$type, levels=c("Insertion","Deletion","Expansion","Contraction"))
2. 多元化作图
# 核密度图的绘制
ggplot(my_data, aes(x=size,fill=type)) + geom_density(alpha=0.5) + xlim(0,500)
# 横向标签为type,这里facet_grid参数是新的,用来多元化作图,y轴表示没有标签
ggplot(my_data, aes(x=size,fill=type)) + geom_density() + xlim(0,500) + facet_grid(type ~ .)
# 只是将标签换到y轴
ggplot(my_data, aes(x=size,fill=type)) + geom_density() + xlim(0,500) + facet_grid(. ~ type)
# facet_grid的语法(行~列)
# plot + facet_grid(rows ~ columns)
# Facet on type and chrom
ggplot(my_data, aes(x=size,fill=type)) + geom_density() + xlim(0,500) + facet_grid(chrom ~ type)
ggplot(my_data, aes(x=size,fill=type)) + geom_density() + xlim(0,500) + facet_grid(type ~ chrom)
# bar图
ggplot(my_data, aes(x=size,fill=type)) + geom_bar() + xlim(0,500) + facet_grid(chrom ~ type)
# 箱线图
ggplot(my_data, aes(x=type,y=size,color=type,fill=type)) + geom_boxplot() + facet_grid(chrom ~ .)
# 小提琴图
ggplot(my_data, aes(x=type,y=size,color=type,fill=type)) + geom_violin() + facet_grid(chrom ~ .)
# 几何点
ggplot(my_data, aes(x=ref.dist,y=query.dist,color=type,fill=type)) + xlim(0,500) + ylim(0,500) + geom_point() + facet_grid(chrom ~ type)
# dotplot图
ggplot(my_data, aes(x=size,fill=type)) + geom_dotplot() + xlim(5000,10000) + facet_grid(chrom ~ type)
3.内置图片
# Inset figures:
#使用第五节课的图片参数
theme_set(theme_gray() +
theme(
axis.line = element_line(size=0.5),
panel.background = element_rect(fill=NA,size=rel(20)),
panel.grid.minor = element_line(colour = NA),
axis.text = element_text(size=16),
axis.title = element_text(size=18)
)
)
# 大图的绘制
big_plot <- ggplot(my_data, aes(x=size,fill=type)) +
geom_bar(binwidth=100) +
guides(fill=FALSE) +
scale_y_continuous(expand=c(0,0)) # Move bars down to X-axis
big_plot
# 小图绘制
small_plot <- ggplot(my_data, aes(x=size,fill=type)) + geom_bar(binwidth=5) + xlim(0,500) + theme(axis.title=element_blank()) + scale_y_continuous(expand=c(0,0))
small_plot
# 在大图中插入小图
library(grid)
vp <- viewport(width = 0.8, height = 0.7, x = 0.65, y = 0.65)
# width, height, x-position, y-position of the smaller plot
png("Lesson-07/inset_plot.png")
print(big_plot)
print(small_plot, vp = vp)
dev.off()
从上星期一直拖到了现在,加上现在有些感冒,真的有点晕了,果然还是需要有连续性。很多地方需要继续补充说明,现在也只是大致的学习一遍。