[英]Overlaying subplot ggraph
我需要在ggraph上覆蓋一組子圖 。 每個圖都對應一個特定的節點,因此必須使用每個節點的坐標來放置它們。 以下代碼創建圖形和要覆蓋的子圖組。
# Create the graph
library(data.table)
library(igraph)
library(ggraph)
mydata <- data.table(from=c("John", "John", "Jim"), to=c("John", "Jim", "Jack"))
graph <- graph_from_data_frame(mydata)
V(graph)$class <- c("John", "Jim", "Jack")
ggraph(graph, layout = 'linear') +
geom_edge_link() +
geom_node_point() +
geom_node_text(aes(label = class))
# Plots to overlay
John <- ggplot(diamonds, aes(carat)) + geom_histogram(fill = "red") +
ggtitle("John")
Jim <- ggplot(diamonds, aes(depth)) + geom_histogram(fill = "blue") +
ggtitle("Jim")
Jack <- ggplot(diamonds, aes(price)) + geom_histogram(fill = "green") +
ggtitle("Jack")
您可以使用ggraph::create_layout
提取節點的x和y坐標,然后使用purrr::pmap
將ggplot2::annotation_custom
應用於每個子圖。
library(purrr)
library(ggplot2)
library(igraph)
library(ggraph)
# Your code, mostly unchanged (removed data.table)
mydata <- data.frame(from=c("John", "John", "Jim"), to=c("John", "Jim", "Jack"))
graph <- graph_from_data_frame(mydata)
V(graph)$class <- c("John", "Jim", "Jack")
John <- ggplot(diamonds, aes(carat)) + geom_histogram(fill = "red") +
ggtitle("John")
Jim <- ggplot(diamonds, aes(depth)) + geom_histogram(fill = "blue") +
ggtitle("Jim")
Jack <- ggplot(diamonds, aes(price)) + geom_histogram(fill = "green") +
ggtitle("Jack")
# New code
graph_df <- create_layout(graph, layout = 'linear')
graph_df
是一個包含以下內容的數據graph_df
:
xy name class ggraph.orig_index circular ggraph.index 1 1 0 John John 1 FALSE 1 2 2 0 Jim Jim 2 FALSE 2 3 3 0 Jack Jack 3 FALSE 3
您可以直接調用ggraph(graph_df)
; 在引擎蓋下ggraph(graph)
正在執行相同的步驟。
現在,我們創建一個嵌套列表,其中第一個元素是要用於插入的ggplot對象的列表(確保它們相對於graph_df
中的順序,順序graph_df
)。 第二個元素是x坐標的列表,第三個元素是y坐標的列表。 然后,我們使用一個構造grobs來插入的函數,使用x和y坐標定義一個將在最終繪圖中顯示的框。
grobs <- pmap(.l = list(plots = list(John, Jim, Jack),
x = as.list(graph_df$x),
y = as.list(graph_df$y)),
.f = function(plots, x, y) {
annotation_custom(grob = ggplotGrob(plots + theme_grey(base_size = 4)),
xmin = x - .25, xmax = x + .25,
ymin = y + .1, ymax = y + .6)
})
然后,您上面的代碼僅需要添加此對象,並需要對限制進行擺弄:
ggraph(graph_df) +
geom_edge_link() +
geom_node_point() +
geom_node_text(aes(label = class)) +
expand_limits(x = c(0.5,3.5)) +
coord_equal() +
grobs
一些注意事項:
purrr
函數以編程方式完成。 base_size =
參數需要根據您的喜好進行調整。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.