问题描述
我有一个很大的数据集,但让我们举一个玩具示例:
I have a large dataset but let's put a toy example:
mydata <- data.table(from=c("John", "John", "Jim"),to=c("John", "Jim", "Jack"))
nodesd=unique(c(mydata$from, mydata$to))
nodes <- create_node_df( n=length(nodesd), label=nodesd, type=nodesd)
edges <- create_edge_df(from = mydata$from, to = mydata$to, rel = "leading_to")
graph <- create_graph( nodes_df = nodes, edges_df = edges)
render_graph(graph)
但我明白了:
而不是预期的结果:
我使用第一个 igraph 得到了那个,但我想避免这一步.
I got that one using first igraph, but I'd like to avoid that step.
更新:
library(data.table)
mydata <- data.table(from=c("John", "John", "Jim"),to=c("John", "Jim", "Jack"), stringsAsFactors = T)
mydata 已经在使用因子.我不需要额外的步骤转换因子.
mydata is already using factors. I don't need extra steps converting factors.
我可以用 igraph 创建绘图:
I can create the plot with igraph:
library(igraph)
mygraph <- graph_from_data_frame(d=mydata, directed=T)
plot(mygraph)
或者使用它的对象来构建一个 DiagrammeR 图:
Or use its object to build a DiagrammeR plot:
V(mygraph)$label = V(mygraph)$name
V(mygraph)$name = factor(V(mygraph)$name, levels=as.character(V(mygraph)$name))
mygraph2 <- from_igraph(mygraph)
render_graph(mygraph2)
但现在我尝试直接从 Diagrammer 中完成,没有 igraph:
But now I try to do it directly from Diagrammer, without igraph:
nodesd = unique(unlist(mydata[,.(from,to)]))
nodes <- create_node_df( n=length(nodesd), label=nodesd)
edges <- create_edge_df(from = mydata$from, to = mydata$to, rel = "leading_to")
graph <- create_graph( nodes_df = nodes, edges_df = edges)
render_graph(graph)
有什么问题吗?
推荐答案
我得到了你的第一个代码:
With your 1st code I got:
> mydata <- data.table(from=c("John", "John", "Jim"),to=c("John", "Jim", "Jack"))
> nodesd=unique(c(mydata$from, mydata$to))
> nodes <- create_node_df( n=length(nodesd), label=nodesd, type=nodesd)
> edges <- create_edge_df(from = mydata$from, to = mydata$to, rel = "leading_to")
Warning messages:
1: In create_edge_df(from = mydata$from, to = mydata$to, rel = "leading_to") :
NAs introduced by coercion
2: In create_edge_df(from = mydata$from, to = mydata$to, rel = "leading_to") :
NAs introduced by coercion
> graph <- create_graph( nodes_df = nodes, edges_df = edges)
> render_graph(graph)
正如@user20650 所说,这是性格和因素的问题.所以我做出了改变.
As @user20650 said, it is an issue with character and factors. So I make a change.
mydata <- data.frame(from=c("John", "John", "Jim"),
to=c("John", "Jim", "Jack"))
mydata$from <- as.character(mydata$from)
mydata$to <- as.character(mydata$to)
nodesd = unique(c(mydata$from, mydata$to))
nodes <- create_node_df( n=length(nodesd), label=nodesd, type=nodesd)
edges <- create_edge_df(from = factor(mydata$from, levels = nodesd),
to = factor(mydata$to, levels = nodesd),
rel = "leading_to")
graph <- create_graph(nodes_df = nodes, edges_df = edges)
render_graph(graph)
我得到了下面的结果.
结果:
希望能帮到你.
这篇关于如何使用 DiagrammeR 创建网络图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!