我有一个网络图,我想为边着色以匹配它们各自的节点。这在 igraph
中相当直接情节,但我更喜欢做 ggraph
因为我喜欢包装提供的其他美学。
似乎对 ggraph
中的节点颜色几乎没有控制。 ;而边缘颜色被广泛覆盖。
我的问题是:如何将我的边与使用自定义函数着色的节点进行匹配,以便“离开”节点的每条边的颜色与其节点相同。这应该有助于人们更轻松地通过网络跟踪流量。一个更普遍的问题是:ggraph 如何在美学论证之外分配颜色。我的问题类似于我之前在这里问过的另一个问题,但反过来(将边与节点匹配),发现 here .
这是一个可重现的示例:
library(tidyverse)
library(igraph)
library(ggraph)
library(tidygraph)
library(RColorBrewer)
## the custom function using Color Brewer
cols_f <- colorRampPalette(RColorBrewer::brewer.pal(11, 'Spectral'))
## make the graph
g <- erdos.renyi.game(50, .1)
# provide some names
V(g)$name <- 1:vcount(g)
#plot using ggraph
g %>%
as_tbl_graph() %>%
activate(nodes) %>%
mutate(degree = centrality_degree()) %>%
ggraph()+
geom_edge_fan(aes(color = as.factor(from),
alpha = ..index..),
show.legend = F)+
geom_node_point(aes(size = degree),
color = cols_f(vcount(g)), # custom function for node color
show.legend = F)+
scale_color_manual(values = cols_f(ecount(g)))+ # custom function for edge color
coord_equal()
最佳答案
我个人发现明确地使用 layout
对象有助于理解变量映射。
它具有“layout_igraph”+“layout_ggraph”+“data.frame”类并包含
data.frame
对于其坐标由 create_layout
定义的节点以及 attributes(layout)$graph
)前者由
geom_node_point
访问绘制节点,后者由 geom_edge_fan
绘制边缘。可以使用ggplot2标准
scale_color_manual
控制节点的颜色, 边的颜色与 ggraph 相加 scale_edge_color_manual
.如果 limits
,两者都可以与相同的节点名称~颜色映射一起使用。属性被相应地设置,因为它包含...a character vector that defines possible values of the scale and their order.
library(tidyverse)
library(igraph)
library(ggraph)
library(tidygraph)
## the custom function using Color Brewer
cols_f <- colorRampPalette(RColorBrewer::brewer.pal(11, 'Spectral'))
## make the graph
g <- erdos.renyi.game(50, .1)
# provide some names
V(g)$name <- 1:vcount(g)
# plot using ggraph
graph_tbl <- g %>%
as_tbl_graph() %>%
activate(nodes) %>%
mutate(degree = centrality_degree())
layout <- create_layout(graph_tbl, layout = 'igraph', algorithm = 'nicely')
ggraph(layout) +
geom_edge_fan(
aes(color = as.factor(from), alpha = ..index..),
show.legend = F
) +
geom_node_point(
aes(size = degree, color = as.factor(name)),
show.legend = F
) +
scale_color_manual(
limits = as.factor(layout$name),
values = cols_f(nrow(layout))
) +
scale_edge_color_manual(
limits = as.factor(layout$name),
values = cols_f(nrow(layout))
) +
coord_equal()
关于r - 如何控制ggraph中的节点颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54185514/