gpt4 book ai didi

r - 使用 ggraph/ggplot2 在网络图中定位节点和边

转载 作者:行者123 更新时间:2023-12-04 17:39:25 27 4
gpt4 key购买 nike

我试图用 ggraph 绘制一个网络,我想在图形周围添加一个圆圈,边缘和节点位于圆圈内。

使用以下代码绘制圆圈效果很好(改编自 Draw a circle with ggplot2 )

gg_circle <- function(r, xc, yc, color = "black", fill = NA, lty = NA, size = NA, ...) {
x <- xc + r*cos(seq(0, pi, length.out = 100))
ymax <- yc + r*sin(seq(0, pi, length.out = 100))
ymin <- yc + r*sin(seq(0, -pi, length.out = 100))
annotate("ribbon", x = x, ymin = ymin, ymax = ymax,
color = color, fill = fill, lty = lty, size = size, ...)
}

但是我无法将网络层的位置与圆的位置相匹配,这导致节点和边都部分位于圆外:

see here for a screenshot

这是代码的关键部分,因为它现在是(使用来自 highschoolggraph 作为可重复性目的的示例数据集):
library(ggraph)
library(igraph)
graph <- graph_from_data_frame(highschool)

ggraph(graph, layout = "fr") +
geom_edge_link() +
geom_node_point() +
geom_node_text(aes(label = name),
check_overlap = TRUE, repel = TRUE,
nudge_x = 0.1, nudge_y = 0.1) +
gg_circle(r = 11, xc = 0, yc = 0, lty = 1, size = 0.2) +
theme(axis.ticks.length = unit(0, "cm"),
legend.position = "none",
plot.margin = unit(c(0, 0, 0, 0), "cm"),
panel.spacing = unit(c(0, 0, 0, 0), "cm")) +
coord_fixed()

有关如何解决此问题的任何想法或建议?提前致谢!

最佳答案

我会尝试使用节点位置来为 r 找到可接受的值, xc , 和 yc .

步骤 1 .创建绘图(不带圆圈):

set.seed(9) # for reproducibility

p <- ggraph(graph, layout = "fr") +
geom_edge_link() +
geom_node_point() +
geom_node_text(aes(label = name),
check_overlap = TRUE,
repel = TRUE,
nudge_x = 0.1,
nudge_y = 0.1) +
theme(axis.ticks.length = unit(0, "cm"),
legend.position = "none",
plot.margin = unit(c(0, 0, 0, 0), "cm"),
panel.spacing = unit(c(0, 0, 0, 0), "cm")) +
coord_fixed()

步骤 2 .从绘图的 geom_node_point() 中获取数据层(在这种情况下是第二层)。修改 gg_circle code将此数据框作为输入,并计算适当的圆心坐标/半径:
p.positions <- layer_data(p, i = 2L)

gg_circle_from_position <- function(data,
color = "black", fill = NA,
lty = NA, size = NA, ...){

coord.x <- data[, 'x']
coord.y <- data[, 'y']

xc = mean(range(coord.x))
yc = mean(range(coord.y))
r = max(sqrt((coord.x - xc)^2 + (coord.y - yc)^2)) * 1.05
# expand radius by 5% so that no node sits exactly on the line;
# increase from 1.05 to some larger number if more buffer is desired.

# no change to this part
x <- xc + r*cos(seq(0, pi, length.out = 100))
ymax <- yc + r*sin(seq(0, pi, length.out = 100))
ymin <- yc + r*sin(seq(0, -pi, length.out = 100))
annotate("ribbon", x = x, ymin = ymin, ymax = ymax,
color = color, fill = fill, lty = lty, size = size, ...)

}

步骤 3 .添加圆圈以绘制:
p + gg_circle_from_position(data = p.positions, lty = 1, size = 0.2)

plot

关于r - 使用 ggraph/ggplot2 在网络图中定位节点和边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48549897/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com