坡度图是比较几个点之间的相对位置的一个很好的方法,基本思想是利用折线图来呈现。下面我们以不同时间点的基因表达为例教大家如何绘制坡度图:
library(ggplot2)
library(ggthemes)
# 演示数据
df <- data.frame(
A = c("GENE1", "GENE2", "GENE3", "GENE4", "GENE5"),
B = c(31, 432, 54, 654, 76),
C = c(4, 465, 65, 768, 87),
D = c(32,499,65,657,87)
)
# 定义列名
colnames(df) <- c("GENE", "Time1", "Time2", "Time3")
# 定义标签
t1 <- paste(df$GENE, round(df$Time1), sep = ", ")
t2 <- paste(df$GENE, round(df$Time2), sep = ", ")
t3 <- paste(df$GENE, round(df$Time3), sep = ", ")
# 定义颜色
df$class <- ifelse((df$Time2 - df$Time1) < 0, "red", "green")
# 绘图
ggplot(df) + geom_segment( # 绘制Time1到Time2折线图
aes(
x = 1,
xend = 2,
y = Time1,
yend = Time2,
col = class
),
size = .75,
show.legend = F
) +
geom_segment(# 绘制Time2到Time3折线图
aes(
x = 2,
xend = 3,
y = Time2,
yend = Time3,
col = class
),
size = .75,
show.legend = F
) +
# 添加竖线
geom_vline(xintercept = 1,
# 竖线类型,虚线
linetype = "dashed",
size = .1) +
geom_vline(xintercept = 2,
linetype = "dashed",
size = .1) +
geom_vline(xintercept = 3,
linetype = "dashed",
size = .1) +
scale_color_manual(
labels = c("Up", "Down"),
values = c("green" = "#00ba38", "red" =
"#f8766d")
) + # color of lines
labs(x = "Time", y = "GENE Count") + # 坐标轴标签
# 定义x、y轴范围
xlim(0.5, 3.5) +
ylim(0, (1.1 * (max(
df$Time1, df$Time2, df$Time3
)))) + # X and Y axis limits
# 添加标签
geom_text(
label = t1,
y = df$Time1,
x = rep(1, NROW(df)),
hjust = 1.1,
size = 3.5
) +
geom_text(
label = t2,
y = df$Time2,
x = rep(2, NROW(df)),
hjust = -0.1,
size = 3.5
) +
geom_text(
label = t3,
y = df$Time3,
x = rep(3, NROW(df)),
hjust = -0.1,
size = 3.5
) +
geom_text(
label = "Time 1",
x = 1,
y = 1.1 * (max(df$Time1, df$Time2)),
hjust = 1.2,
size = 5
) + # title
geom_text(
label = "Time 2",
x = 2,
y = 1.1 * (max(df$Time1, df$Time2)),
hjust = -0.1,
size = 5
) + # title
geom_text(
label = "Time 3",
x = 3,
y = 1.1 * (max(df$Time2, df$Time3)),
hjust = -0.1,
size = 5
) +
# 主题
theme_few()
这里主要用了ggplot2的geom_segment
绘制,大家可以根据我给的示例代码学习掌握。
参考资料:
1.http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html#Dot%20Plot