gpt4 book ai didi

r - ggraph树中节点的控制顺序

转载 作者:行者123 更新时间:2023-12-05 03:27:33 25 4
gpt4 key购买 nike

是否可以控制 ggraph 树中节点的水平顺序?

  • 以下代码创建一棵树:
library(ggraph)
library(igraph)
library(tidyverse)

mygraph <- tibble(from = c("A", "A", "C", "C"), to = c( "B", "C", "D", "E")) %>%
graph_from_data_frame()
V(mygraph)$node_label <- names(V(mygraph))
mygraph %>%
ggraph(layout = 'tree', circular = FALSE) +
geom_edge_diagonal(edge_width = 0.12) +
geom_node_label(aes(label=node_label), size = 10,
label.size = 0, label.padding = unit(0.1, "lines")) +
theme_void() +
coord_fixed()
  • 结果树:

enter image description here

我希望能够将节点 B 作为左分支,将节点 C 及其后续节点作为右分支。

最佳答案

图形节点的顺序不对,请先重新排序。 This comment有一个简单的方法,我将在下面使用。

suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(ggraph))
suppressPackageStartupMessages(library(igraph))

mygraph <- tibble(from = c("A", "A", "C", "C"), to = c( "B", "C", "D", "E")) %>%
graph_from_data_frame()

# out of order
names(V(mygraph))
#> [1] "A" "C" "B" "D" "E"

# order the nodes
s <- sort(names(V(mygraph)))
mygraph <- permute(mygraph, match(V(mygraph)$name, s))

reprex package 创建于 2022-03-12 (v2.0.1)

现在分配节点标签并绘制图形。

V(mygraph)$node_label <- names(V(mygraph))

mygraph %>%
ggraph(layout = 'tree', circular = FALSE) +
geom_edge_diagonal(edge_width = 0.12) +
geom_node_label(aes(label=node_label), size = 10,
label.size = 0, label.padding = unit(0.1, "lines")) +
theme_void() +
coord_fixed()

reprex package 创建于 2022-03-12 (v2.0.1)

关于r - ggraph树中节点的控制顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71450071/

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