1

I'm learning to use tidygraph and ggraph to plot social network data. I like it so far, but I can't figure out how to use color gradients to indicate edge direction while also mapping the color (that the gradient is based on) to an edge attribute.

Example data

require(tidygraph)
require(ggraph)

edges_df <- tibble(from = c("A","A","B","C","C","D"),
                   to = c("C","B","D","B","D","A"),
                   edgewidth = c(1,3,3,2,4,1),
                   edgegradient = factor(c("red","blue","red","blue","blue","red"))) 
# I realize edge gradient could be any attribute, not necessarily the names of the desired colors.

nodes_df <- tibble(node_id = c("A","B","C","D"))

my_graph <- tbl_graph(directed = TRUE, nodes = nodes_df, edges = edges_df)

ggraph(my_graph %>%
         activate(edges), layout = "linear", circular = TRUE) +
  geom_edge_arc(aes(width = edgewidth, color = stat(..index..))) +
  geom_node_label(aes(label = node_id), size = 10)

Here is the ggraph plot (since I'm new to SO, I can't embed the image).

What I want: Edges A->C, D->A, and B->D to be a red gradient, and edges A->B, C->B, and C->D to be a blue gradient. I have a feeling I'm confusing what geom_edge_arc's color aesthetic is doing versus what the scale_edge_color_* aesthetic does.

I like that ggraph uses the ggplot engine and similar syntax, so if at all possible, an answer using ggraph would be great. If not, that's okay.

4

1 回答 1

0

也许这就是你要找的。可能有一种解决方案可以通过明确指定的颜色渐变来实现。然而,在看了这个问题之后,获得两种不同“颜色渐变”的简单解决方案是..index..alpha审美上映射,而在边缘梯度上映射color。要获得正确的颜色,您可以使用scale_edge_color_identity

library(tidygraph)
library(ggraph)
library(tibble)

edges_df <- tibble(from = c("A","A","B","C","C","D"),
                   to = c("C","B","D","B","D","A"),
                   edgewidth = c(1,3,3,2,4,1),
                   edgegradient = factor(c("red","blue","red","blue","blue","red"))) 
# I realize edge gradient could be any attribute, not necessarily the names of the desired colors.

nodes_df <- tibble(node_id = c("A","B","C","D"))

my_graph <- tbl_graph(directed = TRUE, nodes = nodes_df, edges = edges_df)

ggraph(my_graph %>%
         activate(edges), layout = "linear", circular = TRUE) +
  geom_edge_arc(aes(width = edgewidth, alpha = stat(..index..), color = edgegradient)) +
  geom_node_label(aes(label = node_id), size = 10) +
  scale_edge_color_identity(guide = "legend")

在此处输入图像描述

于 2020-10-16T07:30:17.897 回答