[英]One line plot per row for multiple rows (ggplot or base R?)
我有以下數據框:
test_new <- structure(list(PS_position = c(12871487, 12997222, 12861487,
12871491, 12934355), Region_ID = structure(c(1L, 1L, 2L, 2L,
1L), .Label = c("D", "D_left", "D_right"), class = "factor"),
chr_key = c(1, 1, 1, 1, 1), start = c(12871487, 12871487,
12871487, 12871487, 12871487), stop = c(12997222, 12997222,
12997222, 12997222, 12997222), exact_center = c(12934355,
12934355, 12934355, 12934355, 12934355)), .Names = c("PS_position",
"Region_ID", "chr_key", "start", "stop", "exact_center"), row.names = c(1L,
2L, 3L, 4L, 7L), class = "data.frame")
我想為每行繪制一個圖,其中每個區域的開始、停止和中心保持不變,並且 PS_position 被逐個添加為一個點,如下所示(圖上不需要有文字,PS_position 標記可以是別的):
這在 ggplot 中作為 geom_vline() 和 geom_hline() 很難做到:
ggplot(test_new) + geom_vline(xintercept = 12871487) + geom_vline(xintercept = 12997222) + geom_vline(xintercept = 12934355)
所以我用一個例子嘗試了 base R:
plot(1,1)
lines(c(0.8, 1.2), c(0.6, 0.6))
abline(v = 1, col = "gray60")
abline(v=1.2, col = "gray60")
abline(v=0.8, col = "gray60")
很明顯,這些策略離期望的情節還有很長的路要走。 所以我的問題是如何最好地為單行制作所需的圖,以及如何迭代它以保持前一行的點數?
非常感謝!
Reduce(
function(plot, position) {
plot + annotate(
geom = "point",
x = position, y = 1,
shape = 18, size = 5)
},
test_new$PS_position,
init = ggplot() +
theme_minimal() +
theme(
panel.grid =element_blank(),
axis.text = element_blank(),
axis.line = element_blank()) +
labs(x = NULL, y = NULL) +
geom_vline(xintercept = c(12871487, 12934355, 12997222), color = "red"),
accumulate = TRUE)
將構建一個包含迭代添加點的圖列表,看起來非常接近您的想法,最后一個圖看起來像這樣
使用 dplyr、tidyr 和 purrr 按數據框分組。 這只是按 Region_ID 分組,為列中的每個數據幀嵌套和運行相同的減少
library(dplyr)
library(purrr)
library(tidyr)
test_new %>%
group_by(Region_ID) %>%
nest() %>%
mutate(plots = map(data, ~Reduce(
function(plot, position) {
plot + annotate(
geom = "point",
x = position, y = 1,
shape = 18, size = 5)
},
.$PS_position,
init = ggplot() +
theme_minimal() +
theme(
panel.grid =element_blank(),
axis.text = element_blank(),
axis.line = element_blank()) +
labs(x = NULL, y = NULL) +
geom_vline(xintercept = c(12871487, 12934355, 12997222), color = "red"),
accumulate = TRUE)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.