ell*_*iot 5 r colors nodes ggraph
我有一个网络图,我想为边着色以匹配它们各自的节点。这在igraph情节中相当直接,但我更喜欢这样做,ggraph因为我喜欢包提供的其他美学。
似乎对ggraph; 中的节点颜色几乎没有控制。而边缘颜色被广泛覆盖。
我的问题是:如何将我的边与使用自定义函数着色的节点进行匹配,以便“离开”节点的每条边的颜色与其节点相同。这应该有助于人们更轻松地通过网络跟踪流量。一个更普遍的问题是:ggraph 如何在美学论证之外分配颜色。我的问题类似于我之前在这里问过的另一个问题,但反过来(将边与节点匹配),在这里找到。
这是一个可重现的示例:
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()
Run Code Online (Sandbox Code Playgroud)
我个人发现显式地使用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如果相应地设置了属性,则两者都可以与相同的节点名称〜颜色映射一起使用,因为它包含...
定义比例的可能值及其顺序的字符向量。
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()
Run Code Online (Sandbox Code Playgroud)