r - 在 R 中操作“networkD3”对象
问题描述
我正在使用 R 中的 networkD3 库为我的数据创建关系图:
library(igraph)
library(dplyr)
library(networkD3)
#create file from which to sample from
x5 <- sample(1:1000000000, 2000, replace=T)
#convert to data frame
x5 = as.data.frame(x5)
#create first file (take a random sample from the created file)
a = sample_n(x5, 1000)
#create second file (take a random sample from the created file)
b = sample_n(x5, 1000)
#combine
c = cbind(a,b)
#create dataframe
c = data.frame(c)
#rename column names
colnames(c) <- c("a","b")
#convert to factors
c$a = as.factor(c$a)
c$b = as.factor(c$b)
#plot graph (with networkD3)
c = data.frame(c)
simpleNetwork(c, fontSize= 20, zoom = T)
当我制作这个图表时,我发现输出不是很容易查看和操作。
我正在尝试使用 forcegraph 布局,但我在使用它时遇到了困难:
forceNetwork(Links = c$b, Nodes = c$a,
Source = "source", Target = "target",
Value = "value", NodeID = "c$a",
opacity = 0.8)
有人可以告诉我我做错了什么吗?
解决方案
据我了解,forceNetwork
与simpleNetwork
.
Links 参数需要一个表来保存节点表中存储的节点的索引(2 列:'from' - 'to',或如示例中的'source' - 'target')。请注意,索引应该从 0 而不是 1 开始。“链接”的第三列应该是边缘宽度。
Nodes 参数需要一个包含 1) 名称和 2) 组的表。
您在示例中使用的附加参数是您在“链接”和“节点”中使用的表中相应列的列名。例如,当您使用NodeID = "c$a"
这意味着您的节点表有一个名为“c$a”的列。
看看帮助页面:?forceNetwork
他们比我更好地描述了参数,但也向下滚动到示例并检查其示例数据的形状(MisLinks 和 MisNodes)。
也许这个小代码可以给你一个方向(继续你的'c'对象):
c$a = as.character(c$a)
c$b = as.character(c$b)
Nodes_IDs <- data.frame(name=sort(unique(c(c$a, c$b))))
Nodes_IDs$gr <- 1
# JavaScript need zero-indexed IDs.
c$a <- match(c$a, Nodes_IDs[,1]) -1
c$b <- match(c$b, Nodes_IDs[,1]) -1
c$width <- .5
forceNetwork(Links = c, Nodes = Nodes_IDs,
Source = "a", Target = "b",
Value = "width", NodeID = "name",
Group = "gr",
opacity = 0.8)
推荐阅读
- javascript - 如果 HTML 选择器具有特定值,如何运行 Java Script 函数?
- javascript - 无法使用 Fetch API 从 MySQL 数据库中获取数据
- javascript - Flutter WebView:从呈现的 URL 中检索所有完全生成的 html(类似于“检查元素”)
- html - 为什么我需要两次应用 flexbox 才能让它工作?
- javascript - 为什么我的网页中没有显示 JSON 更新?
- python - 我的 SGD 实现有问题
- c++ - 当我尝试在 getline 中提供用户输入时,光标仍保留在最后
- rules - 在剪辑中断言字符串
- css - 从 FullCalendar v5 中删除日历的外部边界
- python - 用于 Python 中的循环,但步长为“n”