数据
df <- data.frame(x = 1:10, y = 1:10, row.names = paste0("s", 1:10))
metadata <- data.frame(f1 = c(rep("A", 5), rep("B", 5)),
f2 = c(rep("C", 3), rep("D", 4), rep("E", 3)),
row.names = paste0("s", 1:10))
结果存储
outdir <- "plots"
if(! dir.exists(outdir)) { # 判断目录是否存在
dir.create(outdir) # 创建目录
}
做图
1. 散点图 (scatter plot)
library(ggplot2)
library(ggpubr)
# scatter plot
Scatter_plot <- function(df, metadata) {
identical(rownames(df), rownames(metadata)) # 判断df和metadata的行名是否完全一致(内容和顺序)
data <- cbind(df, metadata) # 按列合并df和metadata
ggplot(data, aes(x = x, y = y, color = f1)) +
geom_point() +
geom_smooth(method = lm, linetype = 1, se = FALSE, span = 1) + # 趋势线
stat_cor(method = "spearman",label.x = 4, label.y = 9) + # library(ggpubr)
expand_limits(x = c(0, 12), y = c(0, 12)) + # 设置坐标轴范围
xlab("X") + # 设置X轴名称
ylab("Y") + # 设置Y轴名称
scale_color_discrete(name = "Group") + # 设置图例名称
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5))
}
scatter_plot <- Scatter_plot(df, metadata)
ggsave(filename = paste0(outdir, "/scatter_plot.pdf"), plot = scatter_plot, width = 5, height = 5)
2. 箱型图 (box plot)
# box plot
Boxplot <- function(df, metadata) {
identical(rownames(df), rownames(metadata)) # 判断df和metadata的行名是否完全一致(内容和顺序)
data <- cbind(df, metadata) # 按列合并df和metadata
ggplot(data, aes(x = f1, y = y, color = f1)) +
geom_boxplot(outlier.shape = NA) +
scale_colour_manual(values = brewer.pal(8, "Pastel2")) +
geom_jitter(aes(color = f1), shape = 1, width = 0.2) +
facet_wrap(~f1 + f2, scales = "free_x") +
xlab("X") +
ylab("Y") +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank())
}
boxplot <- Boxplot(df, metadata)
ggsave(filename = paste0(outdir, "/box_plot.pdf"), plot = scatter_plot, width = 5, height = 5)
# box plot with wilcoxon test
Boxplot2 <- function(df, metadata) {
identical(rownames(df), rownames(metadata)) # 判断df和metadata的行名是否完全一致(内容和顺序)
data <- cbind(df, metadata) # 按列合并df和metadata
ggplot(data, aes(x = f2, y = y, color = f2)) +
geom_boxplot(outlier.shape = NA) +
scale_colour_manual(values = brewer.pal(8, "Pastel2")) +
geom_jitter(aes(color = f2), shape = 1, width = 0.2) +
geom_signif(comparisons = list(c("C", "D"), c("C", "E")),
test = "wilcox.test", textsize = 2, step_increase = 0.1,
test.args = list(exact = FALSE, correct = FALSE, conf.int = TRUE,
conf.level = 0.95)) + # 添加wilcoxon test结果,并使不同分组的检验间隔0.01
xlab("X") +
ylab("Y") +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank())
}
boxplot2 <- Boxplot2(df, metadata)
ggsave(filename = paste0(outdir, "/box_plot2.pdf"), plot = boxplot, width=5, height=5)
3. 柱状图 (bar plot)
4. 堆积柱状图 (stacked bar chart)
5. 热图 (heatmap)
6. 三元相图 (Ternary plot)
代码